clicked() signal for QWidget breaks stylesheets

£可爱£侵袭症+ 提交于 2019-12-13 19:38:12

问题


I want to connect clicked() signal of QWidget-container to my slot. So I wrote this code:

hpp:

class LinkWidget : public QWidget
{
    Q_OBJECT

public:
    explicit LinkWidget(QWidget * parent = 0 );
    ~LinkWidget();

signals:
    void clicked();

protected:
    void mousePressEvent(QMouseEvent * event ) ;
};

cpp:

LinkWidget::LinkWidget(QWidget * parent) :
    QWidget(parent)
{

}

LinkWidget::~LinkWidget()
{

}

void LinkWidget::mousePressEvent(QMouseEvent * event)
{
    emit clicked();
}

Everything works fine, but I can't assign stylesheet to this widget anymore:

That works:

QWidget * statuspanel = new QWidget(this);
statuspanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
statuspanel->setMinimumHeight(20);
statuspanel->setMaximumHeight(20);
statuspanel->setStyleSheet("border-bottom: 1px solid rgb(206, 203, 186);"
                           "border-right : 1px solid rgb(206, 203, 186);");

That doesn't:

LinkWidget * statuspanel = new LinkWidget(this);
statuspanel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
statuspanel->setMinimumHeight(20);
statuspanel->setMaximumHeight(20);
statuspanel->setStyleSheet("border-bottom: 1px solid rgb(206, 203, 186);"
                           "border-right : 1px solid rgb(206, 203, 186);");

What am I doing wrong?

Thanks!


回答1:


In order to stylesheets work for direct QWidget subclasses you should reimplement the paintEvent method:

void LinkWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}


来源:https://stackoverflow.com/questions/21020180/clicked-signal-for-qwidget-breaks-stylesheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!