QPushButton 在不同状态显示不同图片
时间: 2024-09-26 07:18:33 浏览: 82
QPushButton在不同状态下显示不同图片,主要是通过设置其按下样式、正常样式和禁用样式。你可以使用QPalette和QIcon来实现这个功能。以下是一个基本的例子:
1. 首先,你需要准备一些图标,比如pressed.png(按下状态)、normal.png(正常状态)和disabled.png(禁用状态)。
2. 在UI设计阶段,将QPushButton添加到窗体上,为其设置默认图标(正常状态):
```cpp
QPushButton *button = new QPushButton(QIcon(":/normal.png"), "按钮文字", this);
```
这里的`:/:normal.png`是资源路径,确保这些图片文件已经放在项目的资源目录下。
3. 使用QPalette改变不同状态下的背景色和图标:
```cpp
// 按下状态
button->setStyleSheet("background-color: #your_pressed_color; border-image: url(:/pressed.png);");
// 正常状态
button->changeEvent(QEvent::Change) {
if (event.type() == QEvent::StyleChange) {
button->setIcon(QIcon(":/normal.png"));
// 更改其他外观属性如颜色
}
}
// 禁用状态
button->setEnabled(false);
button->setStyleSheet("background-color: #your_disabled_color; border-image: url(:/disabled.png);");
```
当QPushButton的状态发生变化时,如鼠标按下、失去焦点等,事件处理函数会更改相应的样式。
阅读全文
相关推荐


















