Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

qt - How to draw control with QStyle and with specified QSS?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...