gpt4 book ai didi

c++ - Qt事件过滤器隐藏widget

转载 作者:行者123 更新时间:2023-11-28 02:29:09 25 4
gpt4 key购买 nike

我有一个父小部件,我必须在其中放置一个自定义小部件(比如 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 按钮不可见,但它们在那里,因为当我将鼠标悬停在它们应该在的位置上时,光标会变成指针。

我做错了什么,我该如何让它发挥作用?

最佳答案

  1. 您忘记在 ChildWidget 声明中添加 Q_OBJECT
  2. 您需要跟踪鼠标 (setMouseTracking(true))
  3. 您需要为您的小部件设置setAttribute(Qt::WA_Hover)
  4. 确保您确实需要在事件过滤器中return true;,而不是返回QWidget::eventFilter(obj, event);。您不需要过滤掉悬停事件。

关于c++ - Qt事件过滤器隐藏widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com