Style sheets with custom widgets and inheritance



  • I've gotten myself in a bit of a dilemma and I'm not really sure what I have to do. I've create my own super class MyWidget (similar to QWidget) which handles style sheets on behalf of subclasses.

    @class MyWidget : public QWidget
    {

    public:

    setBorder(int width)
    {
    setStyleSheet("QWidget#" + objectName()
    + "{border-style: solid; border-width: " + QString::number(width) + "px;}");
    }

    protected:

    void paintEvent(QPaintEvent *event)
    {
    QStyleOption option;
    option.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
    QWidget::paintEvent(event);
    }

    };@

    @class AnotherWidget : public MyWidget
    {

    public:

    AnotherWidget() : MyWidget()
    {
    setBorder(10);
    }

    };@

    AnotherWidget is a complex widget, containing a number of other MyWidgets itself. So when I set the border in AnotherWidget I only want that widget and NOT any the widgets it contains to have a border. For that reason I use objectName() in MyWidget::setBorder. The problem is that the objectName is only set once the constructor returns. That means that when I call setBorder in the constructor the object doesn't have a name. I also can't set a custom object name in setBorder, because the object name will change again after the constructor returns (hence now my style sheet has a different object name than the actual object).

    Any suggestions on a fix for this? I have a couple of ideas, but they are all in the paintEvent and causes my application to constantly run on 90% CPU power, so not a feasible solution.



  • You should declare your AnotherWidget to the Qt metatype system by using the Q_OBJECT macro.
    Then you can use the AnotherWidget as a class (same as MyWidget) in your stylesheets.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.