動態(tài)屬性
在開發(fā)過程中經常碰到控件在不同情況下需要不同的狀態(tài)顯示,在沒了解Qt動態(tài)屬性的用法時塑陵,我都是在代碼中用setStyleSheet根據(jù)不同情況設置不同的樣式,這種做法比較麻煩蜡励,而且不夠靈活令花。
示例
接下來以窗口最大化/還原按鈕為例進行示例說明。
正常狀態(tài)
|
最大化
|
---|
源碼
void Widget::setMaxButtonProperty()
{
m_buttonMax->setProperty("maximizeProperty", this->isMaximized() ? true : false);
m_buttonMax->style()->unpolish(m_buttonMax); //先卸載之前的樣式
m_buttonMax->style()->polish(m_buttonMax); //重新加載樣式
或者
// m_buttonMax->setStyle(QApplication::style())
m_buttonMax->update();
}
如果之前已經設置了樣式凉倚,需要重新設置時需要調用unpolish卸載之前的樣式彭则,當前你也可以直接使用setStyle(QApplication::style())
一步到位
Qss
QPushButton#title_max[maximizeProperty=false]
{
width: 40px;
height: 40px;
background: transparent;
border-image: url("://img/title/btn_max_normal.png")
}
QPushButton#title_max[maximizeProperty=false]:hover
{
border-image: url("://img/title/btn_max_hover.png")
}
QPushButton#title_max[maximizeProperty=true]
{
width: 40px;
height: 40px;
background: transparent;
border-image: url(":/img/title/btn_maxTonormal_normal.png")
}
QPushButton#title_max[maximizeProperty=true]:hover
{
border-image: url(":/img/title/btn_maxTonormal_hover.png")
}
原始屬性
任何被Q_PROPERTY聲明的屬性都能在QSS中使用qproperty-<property name>
語法進行設置。
以QToolButton為例占遥,QToolButton繼承至QAbstractButton俯抖,QAbstractButton擁有以下被Q_PROPERTY聲明的屬性,子類也可通過QSS使用父類中被Q_PROPERTY聲明的屬性,如下,text瓦胎、icon芬萍、iconSize等屬性均可在QSS中使用尤揣。
class Q_WIDGETS_EXPORT QAbstractButton : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText)
Q_PROPERTY(QIcon icon READ icon WRITE setIcon)
Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize)
#ifndef QT_NO_SHORTCUT
Q_PROPERTY(QKeySequence shortcut READ shortcut WRITE setShortcut)
#endif
Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable)
Q_PROPERTY(bool checked READ isChecked WRITE setChecked DESIGNABLE isCheckable NOTIFY toggled USER true)
Q_PROPERTY(bool autoRepeat READ autoRepeat WRITE setAutoRepeat)
Q_PROPERTY(bool autoExclusive READ autoExclusive WRITE setAutoExclusive)
Q_PROPERTY(int autoRepeatDelay READ autoRepeatDelay WRITE setAutoRepeatDelay)
Q_PROPERTY(int autoRepeatInterval READ autoRepeatInterval WRITE setAutoRepeatInterval)
Q_PROPERTY(bool down READ isDown WRITE setDown DESIGNABLE false)
....
}
示例
QToolButton
{
qproperty-text: "QSS使用屬性1";
qproperty-icon: url(://img/cat.png);
qproperty-iconSize: 121px 121px;
}
效果圖
QSS使用屬性.png
參考博文:https://blog.csdn.net/liang19890820/article/details/51693956