Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt add a widget inside another widget?

I'd like to make a single widget that combines the behavior of two existing widgets. For example a widget that is a button that also contains a checkbox. The user can click the larger button but also the checkbox within.

E.g. gmail introduced a "select-all" button that displays a menu on click, but it also integrates a checkbox that selects all email. See this screenshot for an example:
enter image description here


How would one go about combining behaviors of existing widgets to this effect? I'm hoping for a solution where widget behaviors can be combined and I only need to override where they conflict.

This question is similar to the Combine multiple widgets into one in qt question but differs in that I want the two widgets to be placed on top of each other and appear as one widget.

In response to cbamber85's reply I've added the code below to show how far I've managed to integrate the replies. As with cbamber85's reply this contains no real functionality, it's just the PyQT version of his code.

from PyQt4 import QtCore, QtGui

class CheckBoxButton(QtGui.QWidget):
    checked = QtCore.pyqtSignal(bool)

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        self._isdown = False
        self._ischecked = False

    def isChecked(self):
        return self._ischecked

    def setChecked(self, checked):
        if self._ischecked != checked:
            self._ischecked = checked
            self.checked.emit(checked)

    def sizeHint(self, *args, **kwargs):
        QtGui.QWidget.sizeHint(self, *args, **kwargs)
        return QtCore.QSize(128,128)

    def paintEvent(self, event):
        p = QtGui.QPainter(self)
        butOpt = QtGui.QStyleOptionButton()
        butOpt.initFrom(self)
        butOpt.state = QtGui.QStyle.State_Enabled
        butOpt.state |= QtGui.QStyle.State_Sunken if self._isdown else QtGui.QStyle.State_Raised

        self.style().drawControl(QtGui.QStyle.CE_PushButton, butOpt, p, self)

        chkBoxWidth = self.style().pixelMetric(QtGui.QStyle.PM_CheckListButtonSize,
                                               butOpt, self) / 2
        butOpt.rect.moveTo((self.rect().width() / 2) - chkBoxWidth, 0)

        butOpt.state |= QtGui.QStyle.State_On if self._ischecked else QtGui.QStyle.State_Off
        self.style().drawControl(QtGui.QStyle.CE_CheckBox, butOpt, p, self)

    def mousePressEvent(self, event):
        self._isdown = True
        self.update()

    def mouseReleaseEvent(self, event):
        self.setChecked(not self.isChecked())
        self._isdown = False
        self.update()


class Dialog(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        widg = CheckBoxButton(self)
        self.setCentralWidget(widg)


if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = Dialog()
    window.show()
    app.exec_()
like image 703
Jon Lauridsen Avatar asked Aug 08 '12 11:08

Jon Lauridsen


1 Answers

Yes of course you can, but how easy it is depends how the widgets are to be combined.

For example if you want to create a button that has a label next to it rather than inside, you derive from QWidget, add your QLabel and QPushButton as members and then simply append them to the widget's internal layout in the constructor. (I should point out that there are many different ways of doing this).

However, for widgets that combine behaviours into a new, visually different widget - you need to tell Qt how to paint it. So subclass paintEvent(..) and draw your widget manually onto a QPainter(this). And to match the widget to the current style, you'll have to get QStyle to do the component drawing for you - which actually makes life a lot easier.

Then you need to override mouse###Event(..) and manually handle mouse interaction (and may want keyboard interaction too).

It's laborious, but naturally there's less work the closer your widget is to an existing one. In your case I would derive from QToolButton as it already supports drop down menus. Then reimplement paintEvent(..), call QStyle::drawControl(CE_PushButtonBevel, ... to draw the button, and then QStyle::drawControl(CE_CheckBox, ... to draw the checkbox in the correct state. Then reimplement mousePressEvent(..), work out if within the checkbox hit area, and change state accordingly.

A Ridiculous Example

This pointless widget demonstrates some of the techniques described above.

class WeirdCheckBoxButton : public QWidget
{
    Q_OBJECT

public:
    explicit WeirdCheckBoxButton( QWidget* parent = nullptr )
             : QWidget( parent ), checked_( false ), down_( false ) {}
    virtual ~WeirdCheckBoxButton() {}

    bool isChecked() const { return checked_; }
    QSize sizeHint () const { return QSize( 128, 128 ); }

public slots:
    virtual void setChecked( bool checked )
    {
        if ( checked_ != checked ) {
            checked_ = checked;
            emit clicked( checked );
        }
    }

signals:
    void clicked( bool checked );

protected:
    virtual void paintEvent( QPaintEvent* event )
    {
        Q_UNUSED( event )
        QPainter p( this );

        //  QStyleOption, and derived classes, describe the state of the widget.
        QStyleOptionButton butOpt;
        butOpt.initFrom( this ); // A convenience function that steals state
                                 // from this widget.
        butOpt.state = QStyle::State_Enabled;
        butOpt.state |= down_ ? QStyle::State_Sunken : QStyle::State_Raised;

        //  Renders the widget onto the QPainter.
        style()->drawControl( QStyle::CE_PushButton, &butOpt, &p, this );

        //  pixelMetric() gives you style relevant dimensional data.
        int chkBoxWidth = style()->pixelMetric( QStyle::PM_CheckListButtonSize,
                                                &butOpt, this ) / 2;
        butOpt.rect.moveTo( ( rect().width() / 2 ) - chkBoxWidth, 0 );
        butOpt.state |= checked_ ? QStyle::State_On : QStyle::State_Off;
        style()->drawControl( QStyle::CE_CheckBox, &butOpt, &p, this );
    }

    virtual void mousePressEvent( QMouseEvent* event )
    {
        Q_UNUSED( event )

        down_ = true;
        update();
    }

    virtual void mouseReleaseEvent( QMouseEvent* event )
    {
        Q_UNUSED( event )

        setChecked( !isChecked() );
        down_ = false;
        update();
    }

private:
    bool checked_;
    bool down_;
};

It's a thin example, but it's ripe for copying and experimenting on. For example by accessing butOpt.palette, you can tweak the colours of rendered widgets depending on their state.

like image 110
cmannett85 Avatar answered Oct 31 '22 20:10

cmannett85