我试图在悬停和按下时更改QpushButton的图标,我在样式表中使用QtDesigner。我试过这个
QpushButton{
qproperty-icon:url(:/images/start.png);
}
QPushButton:hover
{
qproperty-icon:url(:/images/start_hov.png);
}
但不起作用。
我试着从QtDesigner菜单中设置它,但效果不太好。
发布于 2016-10-29 19:32:13
不幸的是,它是一个尚未修复的Qt缺陷。该bug的注释中有一个变通建议,基本上您可以使用空qproperty-icon
并为其保留必要的空间,同时实际上更改background-image
属性:
QPushButton {
qproperty-icon: url(" "); /* empty image */
qproperty-iconSize: 16px 16px; /* space for the background image */
background-image: url(":/images/start.png");
background-repeat: no-repeat;
}
QPushButton:hover {
background-image: url(":/images/start_hov.png");
background-repeat: no-repeat;
}
但最终结果看起来..。真的不太满意。如果在运行时使用C++更改按钮的图标,可以获得更好的结果,下面是一个使用事件筛选器的简单示例:
#include <QObject>
#include <QPushButton>
#include <QEvent>
class ButtonHoverWatcher : public QObject
{
Q_OBJECT
public:
explicit ButtonHoverWatcher(QObject * parent = Q_NULLPTR);
virtual bool eventFilter(QObject * watched, QEvent * event) Q_DECL_OVERRIDE;
};
ButtonHoverWatcher::ButtonHoverWatcher(QObject * parent) :
QObject(parent)
{}
bool ButtonHoverWatcher::eventFilter(QObject * watched, QEvent * event)
{
QPushButton * button = qobject_cast<QPushButton*>(watched);
if (!button) {
return false;
}
if (event->type() == QEvent::Enter) {
// The push button is hovered by mouse
button->setIcon(QIcon(":/images/start_hov.png"));
return true;
}
if (event->type() == QEvent::Leave){
// The push button is not hovered by mouse
button->setIcon(QIcon(":/images/start.png"));
return true;
}
return false;
}
然后在代码中的某个位置设置UI,您可以执行如下操作:
ButtonHoverWatcher * watcher = new ButtonHoverWatcher(this);
ui->pushButton->installEventFilter(watcher);
和宾果-你得到按钮的图标改变在悬停和取消!
发布于 2018-11-26 18:22:14
在阅读了这篇文章之后遇到了类似的问题。这是我在c++中的工作,没有使用设计人员的样式表。
1>I创建图标,一个用于按下,另一个用于正常。在你的情况下,我们会把它作为悬停条件来处理。
将图标2>Add到资源文件。
3>Use下列代码以供参考..。
其中Add_PB是QPushButton。
Add_PB->setStyleSheet( "*{border-image: url(:/icons/maximize.bmp);}"
":pressed{ border-image: url(:/icons/maximize_pressed.bmp);}");
这里的关键是您可以使用setStyleSheet为不同的条件设置不同的图标。在使用CSS字符串中的*运算符或"Universal“之前,我无法让上面的代码工作。
发布于 2018-03-07 12:46:58
我是在designer中使用ui_...h文件制作的:
QIcon icon;
icon.addFile(QStringLiteral(":/unpressed.png"), QSize(), QIcon::Normal, QIcon::Off);
icon.addFile(QStringLiteral(":/pressed.png"), QSize(), QIcon::Normal, QIcon::On);
pushButton->setIcon(icon);
https://stackoverflow.com/questions/40318759
复制相似问题