gpt4 book ai didi

c++ - Qt eventfilter 不检测 objectName

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:50 26 4
gpt4 key购买 nike

我的程序使用一个 ui-form-file,它在其他小部件旁边包含一个名为“grip”(其对象名称)的标签。当我运行代码时,我看到代码行 grip was not detected 并且我想知道为什么无法识别鼠标点击标签。我还定义了一个 mousePressEvent(QMouseEvent *event),如果我单击该标签,它会按预期工作。

bool Note::eventFilter(QObject *target, QEvent *event)
{
if (event->type()==QEvent::MouseButtonPress){
qDebug() << "in Note::eventFilter" << endl;
if (target->objectName()=="grip")
{
lastClicked="grip";
qDebug() << "lastClicked == grip" << endl;
}
else
qDebug() << "grip was not detected" << endl;
}
return false;
}

target->objectName()=="grip" 可能是什么原因,如果我点击那个目标并且它被称为“grip”?

编辑:我的事件函数就是这样定义的:

void Note::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
qDebug() << "Left mouse button click detected";
...

主事件过滤器在 Note 的构造函数中初始化:

Note::Note(std::vector<Note *> *nListIn){
qDebug() << "in Note::Note()" << endl;
ui.setupUi(this);
installEventFilter(this);
setWindowFlags(Qt::FramelessWindowHint);
this->show(); //must be after the Qt::FramelessWindowHint
nList = nListIn;
nList->push_back(this);
qDebug() << "Size of nList (aka noteList)" << nList->size() << endl;
}

编辑 2:找到一些描述,这可能是原因吗?

If your widget only contains child widgets, you probably do not need to implement any event handlers. If you want to detect a mouse click in a child widget call the child's underMouse() function inside the widget's mousePressEvent().

最佳答案

根据定义,如果您仅在其自身上安装事件过滤器(通过调用 installEventFilter(this),则以下成立:

bool Note::eventFilter(QObject *target, QEvent *) {
Q_ASSERT(target == this);
...
}

显然,目标永远不会被称为 grip,除非您以这种方式命名了 Note 类的实例。

如果你想过滤 handle 标签上的事件,那么你必须在那个标签上安装事件过滤器,而不是在 Note 小部件上。 Note 小部件只会获取 children 忽略的事件,到那时,您“过滤”它们并不重要 - 为时已晚。

您的设置代码可能包含,例如:

ui.grip->installEventFilter(this);

或者,不假设 ui 类的结构:

QWidget * grip = findChild<QWidget*>("grip");
if (grip) grip->installEventFilter(this);

关于c++ - Qt eventfilter 不检测 objectName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21789070/

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