4.31. Custom widgets integration

This section describes how you can extend PyDADL's widgets by creating you own widgets or sub classing PyDADL widgets.

You can integrate a Qt widget (classes that inherits QWidget) into a PyDADL dialog. The following code can be written into the init tag to insert a LCD-like display :

from PyQt4 import QtGui
d.lcd = QtGui.QLCDNumber()
d.lcd.display(123)
d.addWidget(type='custom', custom_widget=d.lcd)

[Note]Note
Obviously you could create your own class that inherits a Qt class and use it in the same manner.

You can also sub class a PyDADL widget and integrate it into a dialog. In this case, you don't have to initiate a class instance, you just pass the class object to the addWidget function. Here is an example taken from PyQt, it is a wiggly label :

<code>
from PyQt4 import QtCore, QtGui
from PyDADL.ui.widgets import Label

class wiggly_label(Label):
    def __init__(self, dialog, name):
        Label.__init__(self, dialog, name)

        font = self.font()
        font.setPointSize(font.pointSize() + 20)
        self.setFont(font)

        self.timer = QtCore.QBasicTimer()

        self.step = 0;
        self.timer.start(60, self)

    def paintEvent(self, event):
        sineTable = [0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38]
        text = self.text()

        metrics = QtGui.QFontMetrics(self.font())
        x = (self.width() - metrics.width(text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QtGui.QColor()

        painter = QtGui.QPainter(self)

        for i in xrange(text.size()):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), QtCore.QString(text[i]))
            x += metrics.width(text[i])

    def timerEvent(self, event):
        if (event.timerId() == self.timer.timerId()):
            self.step = self.step + 1
            self.update()
        else:
            Label.timerEvent(event)

</code>

<init>
d.addWidget('custom', custom_class=wiggly_label, data='Hello world')
</init>

The class that inherits a PyDADL widget must have this __init__ signature : __init__(self, dialog, name), you can add your own arguments afterwards. the custom_args and custom_kwargs arguments of function addWidget can be used as *args and **kwargs to pass custom arguments to you class. Example :

class my_custom_label(Label):
    def __init__(self, dialog, name, text1, text2, text_size=14, text_color='black'):
        Label.__init__(self, dialog, name)
        ...

d.addWidget('custom', custom_class=my_custom_label, custom_args=('first text','second text'), custom_kwargs={'text_size':20})