qt自定义控件组合效果(按钮为例)

Qt组合控件通过QSS实现统一效果

cpp布局代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
textLabel = new QLabel(text, this);
textLabel->setObjectName("textLabel");
textLabel->setAlignment(Qt::AlignCenter);

imageLabel = new QLabel(this);
imageLabel->setObjectName("imageLabel");

QHBoxLayout* hLayout = new QHBoxLayout;
hLayout->setSpacing(SPACING);
hLayout->setContentsMargins(0, 0, 0, 0);

hLayout->addWidget(textLabel, 0, Qt::AlignVCenter);
hLayout->addWidget(imageLabel, 0, Qt::AlignVCenter);

this->setLayout(hLayout);

cpp核心代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
bool Button::event(QEvent* e)
{
switch (e->type())
{
case QEvent::MouseButtonRelease:
setCheckedStage(isChecked());
break;

case QEvent::Enter:
textLabel->setProperty("state", "hover");
imageLabel->setProperty("state", "hover");
repolish(textLabel);
repolish(imageLabel);
break;

case QEvent::Leave:
setCheckedStage(isChecked());
break;

default:
break;
}

return QPushButton::event(e);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void Button::repolish(QWidget* widget)
{
widget->style()->unpolish(widget);
widget->style()->polish(widget);
}

void Button::setCheckedStage(bool isCheck)
{
if (isCheck == true)
{
textLabel->setProperty("state", "checked");
imageLabel->setProperty("state", "checked");
}
else
{
textLabel->setProperty("state", "normal");
imageLabel->setProperty("state", "normal");
}
repolish(textLabel);
repolish(imageLabel);
}
1
2
3
connect(this, &Button::toggled, [=](bool _isChecked) {
setCheckedStage(isChecked());
});

QSS如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.Button
{
background: transparent;
}

.Button QLabel#textLabel[state = 'hover'], .Button QLabel#textLabel[state = 'checked'],
.Button QLabel#imageLabel[state = 'hover'], .Button QLabel#imageLabel[state = 'checked']
{
background:red;
color: white;
}

.Button QLabel#textLabel[state = 'normal'], .Button QLabel#imageLabel[state = 'normal']
{
background:blue;
}

.Button#Temperature QLabel#imageLabel
{
border-image:url(":/image/test.png");
}

总结

  1. 通过事件及Button::toggled信号控制自定义Property,并通过QWidget的style()重新加载其样式;
  2. QSS中判断子控件的自定义Property值来设定相应样式;

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!