1

I'm trying to draw a checkbox in QStyledItemDelegate. I want checkbox to be drawng not with native look, but with style that specified with qApp->setStyleSheet(). I don't know why, but when I draw control with QStyle::drawPrimitive - it doesn't pick up global qss.

Are there any solutions, how to manually draw check box with application style?

Following code and screenshot demonstrate my problem:

CheckBox sample

First check box is draw with QStyle::drawPrimitive, second check box is widget.

#include <QApplication>
#include <QWidget>
#include <QStyle>
#include <QPainter>
#include <QStyleOptionButton>
#include <QCheckBox>

class TestWindow
    : public QWidget
{
    Q_OBJECT

public:
    TestWindow() {}
    ~TestWindow() {}

    void paintEvent( QPaintEvent * event )
    {
        QPainter p( this );

        QStyleOptionButton opt;
        opt.state |= QStyle::State_On;
        opt.state |= QStyle::State_Enabled;
        opt.rect = QRect( 10, 10, 20, 20 );

        style()->drawPrimitive( QStyle::PE_IndicatorCheckBox, &opt, &p, this );
    }
};

int main( int argc, char *argv[] )
{
    QApplication a( argc, argv );

    a.setStyleSheet( "QCheckBox::indicator{ border: 1px solid red; }" );

    TestWindow w;
    QCheckBox *cb = new QCheckBox( &w );
    cb->move( 10, 30 );

    w.show();

    return a.exec();
}

#include "main.moc"

Note: it is possible to create invisible check box and use QPixmap::grabWidget, but this method is too heavy.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61

2 Answers2

3

Qt currently does not support of such drawing:

Warning: Qt style sheets are currently not supported for custom QStyle subclasses. We plan to address this in some future release.

Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
0
QPainter p( this );

QStyleOptionButton opt;
opt.state |= QStyle::State_On;
opt.state |= QStyle::State_Enabled;
opt.rect = QRect( 10, 10, 20, 20 );

QCheckBox cb(this); // create fake checkbox

style()->drawPrimitive( QStyle::PE_IndicatorCheckBox, &opt, &p, &cb); // pass a pointer to checkbox instead of "this"
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
smartgps
  • 9
  • 1
  • 4
    Welcome to Stack Overflow! Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill Mar 18 '15 at 12:14
  • Creating of a widget for each draw call is a non acceptable, heavy overhead. – Dmitry Sazonov Mar 27 '23 at 08:32