[英]Qt eventfilter does not detect objectName
我的程序使用一个ui-form-file,该文件除其他小部件外还包含一个名为“ grip”(其对象名)的标签。 在运行代码时,我看到grip was not detected
代码行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"
为假的原因可能是什么?
编辑:这就是我的事件函数的定义方式:
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:找到一些描述,这可能是原因吗?
如果您的窗口小部件仅包含子窗口小部件,则可能不需要实现任何事件处理程序。 如果要检测鼠标单击子窗口小部件,请在窗口小部件的mousePressEvent()中调用子窗口的underMouse()函数。
根据定义,如果仅在自身上安装事件过滤器(通过调用installEventFilter(this)
,则以下内容成立):
bool Note::eventFilter(QObject *target, QEvent *) {
Q_ASSERT(target == this);
...
}
显然,除非您以这种方式命名了Note
类的实例,否则目标永远不会被称为“ grip
。
如果要过滤夹点标签上的事件,则必须将事件过滤器安装在该标签上,而不是“ Note
小部件上。 Note
窗口小部件将仅获取子级忽略的事件,到那时,“过滤”它们并不重要-为时已晚。
您的设置代码可能包含,例如:
ui.grip->installEventFilter(this);
或者,不假设有关ui
类的结构:
QWidget * grip = findChild<QWidget*>("grip");
if (grip) grip->installEventFilter(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.