Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Style sheets with custom widgets and inheritance
Qt 6.11 is out! See what's new in the release blog

Style sheets with custom widgets and inheritance

Scheduled Pinned Locked Moved General and Desktop
2 Posts 2 Posters 3.2k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    goocreations
    wrote on last edited by
    #1

    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.

    1 Reply Last reply
    0
    • R Offline
      R Offline
      rcari
      wrote on last edited by
      #2

      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.

      1 Reply Last reply
      0

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved