我正在尝试在悬停事件中更改 QPushButton 的图标。 问题是 Qt HoverEnter 事件仅在单击小部件时起作用。 此代码适用于我的配置:https://gist.github.com/peteristhegreat/d6564cd0992351f98aa94f869be36f77 (来自如何在 Qt 中实现 QHoverEvent?) 所以我不明白为什么它在我的情况下不起作用,也许我在 QGraphicsScene 和 QPushButton 之间缺少事件传播标志。 这很令人困惑,因为我已经成功编写了一个代码来处理 QEvent::HoverEnter 但用于滚动区域。
谢谢!
这是我当前的代码(在我的 QGraphicsView 中我使用
my_QGraphicsScene->addWidget(my_hoverBut)
):
#ifndef HOVERBUT_H
#define HOVERBUT_H
#include <QPushButton>
#include <QHoverEvent>
#include <QEvent>
#include <QDebug>
class hoverBut : public QPushButton
{
Q_OBJECT
public:
explicit hoverBut(QWidget *parent = nullptr){
setAttribute(Qt::WA_Hover);
}
protected:
bool event(QEvent * e) override
{
qDebug() << Q_FUNC_INFO << e->type();
switch(e->type())
{
case QEvent::HoverEnter:
case QEvent::HoverLeave:
//Goes here only if clicked
return true;
default:
return QPushButton::event(e);
}
}
};
#endif // HOVERBUT_H
在构建您的小部件时使用
setMouseTracking(true);
。