Define multiple styles for pushbutton control Qt W

2019-07-28 09:01发布

问题:

How can I define multiple styles for one kind of control in one stylesheet? So later developer can select, what kind of style control should looks like.

For example, I need to define two styles for QPushButton: for normal button (on the left) and for action button (on the right)

For the first button I wrote the following style:

QPushButton {
    background-color: #DCDCDC;
    border: 1px solid #BEBEBE;
}
...

And this would apply to all QPushButtons in the project. Next I need to define another action style for QPushButtons also, but which should be selected by developer. How can I do this?

I expect something like this:

QPushButton#ActionButton* {
    background-color: blue;
    border: 1px solid darkerblue;
}

And then if developer will specify objectName of his button starting with "ActionButton" (example "ActionButtonSendRespond") then it will use the second style.

回答1:

You can subclass QPushButton into ActionButton so you can write specific CSS :

C++

#include <QPushButton>

class ActionButton : public QPushButton
{
    Q_OBJECT
public:
    using QPushButton::QPushButton;
};

CSS :

QPushButton {
    background-color: #DCDCDC;
    border: 1px solid #BEBEBE;
}
ActionButton {
    background-color: blue;
    border: 1px solid darkerblue;
}

Then when developers use one class or the other, they know which style will apply. And it can be useful if you also need to change the behaviour in the subclass.