[英]Qt event filter hides the widget
我有一个父窗口小部件,其中必须放置一个自定义窗口小部件(例如QFrame
)。 在该自定义窗口小部件内,我必须放置许多子窗口小部件(来自QPushButton
)。 我希望子小部件在正常情况下具有一定的背景,而将其悬停在另一个背景上。 这是我的代码:
//parent widget code, where the QFrame derived widget is initialized
QFrameDerivedWidget *qFrameWidget = new QFrameDerivedWidget(this, someString);
这是QFrameDerivedWidget
头文件:
//QFrameDerivedWidget header file
class QFrameDerivedWidget: public QFrame
{
Q_OBJECT
public:
QFrameDerivedWidget(QWidget *aParent,
std::string someValue);
bool eventFilter(QObject *obj, QEvent *event);
}
这是QFrameDerivedWidget
实现文件, ChildWidget
类已定义并内联声明:
class ChildWidget: public QPushButton
{
Q_Object
public:
ChildWidget(std::string aText, QWidget *aParent);
};
ChildWidget::ChildWidget(std::string aText, QWidget *aParent):
QPushButton(QString::fromStdString(aText),aParent)
{
this->setFixedHeight(30);
this->setMouseTracking(true);
this->setCursor(Qt::PointingHandCursor);
/* ---other custom styling--- */
}
bool QFrameDerivedWidget::eventFilter(QObject *obj, QEvent *event)
{
// this never prints out anything, even though it should for any mouseenter, mouseleave, click, etc event on it
qDebug() << obj->metaObject()->className() << endl;
if (obj->metaObject()->className() == "ChildWidget")
{
//including this line throws a 'missing QObject missing macro error' as well
ChildWidget *option = qobject_cast<ChildWidget* >(obj);
if (event->type() == QEvent::Enter)
{
option->setStyleSheet("---");
}
if (event->type() == QEvent::Leave)
{
option->setStyleSheet("---");
}
return QWidget::eventFilter(obj, event);
}
else
{
// pass the event on to the parent class
return QWidget::eventFilter(obj, event);
}
}
QFrameDerivedWidget::QFrameDerivedWidget(QWidget *aParent,
std::string someVal): fParent(aParent)
{
initUI();
}
QFrameDerivedWidget::initUI()
{
this->setParent(fParent);
this->setAttribute(Qt::WA_Hover);
this->setMouseTracking(true);
QWidget *dd = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout();
dd->setLayout(layout);
for (int i = 0; i < fValues.size(); i++)
{
ChildWidget *button = new ChildWidget(fValues[i],dd);
button->addEventFilter(this);
layout->addWidget(button);
}
}
这个想法是,每当我将鼠标悬停在QFrameDerivedWidget
并输入任何ChildWidget
,它的背景颜色都应该改变。 另外,我在eventFilter
设置了qDebug()
语句。 当前不起作用, ChildWidget
按钮不可见,但它们在那里,因为当我将鼠标悬停在其应有的位置时,光标会变成指针。
我在做什么错,如何使它正常工作?
ChildWidget
声明中添加Q_OBJECT
宏 setMouseTracking(true)
) setAttribute(Qt::WA_Hover)
为小部件 return true;
在您的事件过滤器中,而不是返回QWidget::eventFilter(obj, event);
。 您不需要过滤掉悬停事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.