實現
1、ui定義出樣式表
// 在最開始的類中右鍵 - 樣式表
QPushButton#button2[test="true"]{color:green;}
QPushButton#button2[test="false"]{color:red;}
2、主類中定義出屬性與實現
#define POLISH(widget) (widget->style()->polish(widget))
class Widget : pulib QWidget
{
Q_OBJECT
Q_PROPERTY(bool test READ getTest WRITE setTest)
public:
Widget(QWidget *parent = nullptr) : QWidget(parent){}
protected:
bool getTest(){return test;}
void setTest(const bool &b){test = b;}
protected slots:
// button1點擊測試 - button2顯示樣式
void on_button1_clicked();
{
static bool b = false;
b = !b;
ui.button2->setProperty("test",b);
// 設置完屬性想要button2更改樣式就必須進行刷新
// 方案1:
ui.button2->style()->polish(ui.button2)
// 方案2 (注意傳入爲指針,該指針不能爲空)
// POLISH(ui.button2);
}
private:
bool test = false;
}
提一句
貌似不需要設置Q_PROPERTY也是可以的哦。只需給對應控件設置屬性值即可,哇哦。
參考
可參考Qt屬性
關注
微信公衆號搜索"Qt_io_"或"Qt開發者中心"瞭解更多關於Qt、C++開發知識.。
筆者 - jxd