gpt4 book ai didi

c++ - Qt:让 parent 决定 child 是否接受事件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:52 29 4
gpt4 key购买 nike

我在尝试获取父对象来过滤子事件时遇到问题。

在下面的示例中,我在旋转框上设置了一个事件过滤器。事件过滤器检测旋转框上的鼠标按下事件。然后,我希望父对象根据某些标准接受或忽略该事件。

问题是它似乎接受了鼠标按下事件,然后忽略了鼠标释放事件。这是鼠标滚轮事件的问题。

我怎样才能让我的 parent 接受/忽略该事件?

在实际情况下,消息必须经过更多层,但行为是相同的。如果您单击旋转框上的向上箭头,将弹出消息,然后数字将开始旋转。

Qt版本:5.6.1

#include "mainwindow.h"

#include <QEvent>
#include <QSpinBox>
#include <QHBoxLayout>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QSpinBox* spinner = new QSpinBox;
QHBoxLayout* layout = new QHBoxLayout;
QWidget* widget = new QWidget;
layout->addWidget(spinner);
spinner->installEventFilter(this);
connect(this, SIGNAL(mouse_pressed(QEvent*)),
this, SLOT(handle_event(QEvent*)));
widget->setLayout(layout);
setCentralWidget(widget);
}

MainWindow::~MainWindow()
{

}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress
event->type() == QEvent::Wheel)
{
emit mouse_pressed(event);
}
return QMainWindow::eventFilter(watched, event);
}

void MainWindow::handle_event(QEvent* event)
{
event->ignore();
QMessageBox(QMessageBox::Warning, "warning", "ignoring event").exec();
}

编辑 1:我找到了部分停止事件级联的方法。在 MainWindow::handle_event(...) 中,我没有调用“event->ignore()”,而是调用“event->setAccepted(false)”,然后在 eventFilter 中检查“event->isAccepted()” .如果不被接受,我将忽略该事件。

此解决方案在 QLineEdit 上运行良好,但在 QSpinBox 和 QPushbutton 上仍无法按预期工作。对于 QSpinBox,滚轮事件仍会更改值并且单击旋转按钮会导致持续旋转(未检测到鼠标释放)。对于 QPushButton,事件被忽略但按钮保持按下状态。

编辑 2: 忽略事件后返回 false 会阻止级联。谢谢@G.M.提示!我会发布一个答案。

最佳答案

让 parent 决定 child 是否应该处理事件的方法是调用“event->setAccepted(false)”,检查 eventFilter 函数中的 。如果为 false,则忽略事件并从函数返回 true。

从 eventFilter 函数返回 true 对我来说是违反直觉的,但它就在文档中。事件过滤器的侵入性比子类化小得多,所以我很高兴找到解决方案。

#include "mainwindow.h"

#include <QEvent>
#include <QSpinBox>
#include <QHBoxLayout>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QSpinBox* spinner = new QSpinBox;
QHBoxLayout* layout = new QHBoxLayout;
QWidget* widget = new QWidget;
layout->addWidget(spinner);
spinner->installEventFilter(this);
connect(this, SIGNAL(mouse_pressed(QEvent*)),
this, SLOT(handle_event(QEvent*)));
widget->setLayout(layout);
setCentralWidget(widget);
}

MainWindow::~MainWindow()
{

}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress
event->type() == QEvent::Wheel)
{
emit mouse_pressed(event);
if (!event->isAccepted())
{
event->ignore();
return true;
}
}
return QMainWindow::eventFilter(watched, event);
}

void MainWindow::handle_event(QEvent* event)
{
event->setAccepted(false);
QMessageBox(QMessageBox::Warning, "warning", "ignoring event").exec();
}

关于c++ - Qt:让 parent 决定 child 是否接受事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776874/

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