我有 stackedWidget,我想捕获他的 child 的所有 mouseClickEvents,独立于他们的类型。它们可以在以后添加和删除(从 stackedWidget 中删除,而不是删除)。我怎样才能使它工作?
最佳答案
您可以在所有子部件上安装事件过滤器,您的事件过滤器可以是新类或现有类,重要的是它实现了 eventFilter 方法并继承自 QObject
一个例子(修改自文档)
bool FilterObject::eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::mousePress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
qDebug() << "Ate mouse press" << mouseEvent->x() << " " << mouseEvent->y();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return FilterObject::eventFilter(obj, event);
}
}
在创建小部件后执行以下操作以安装事件过滤器
FilterObject * filterObj = new FitlerObject(this);
Q_FOREACH(QObject obj, pWin->children())
{
obj->installEventFilter(filterObj);
}
您可以在 http://qt-project.org/doc/qt-4.8/qobject.html#eventFilter 找到完整的文档和 http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter
关于c++ - Qt:在 child 之前捕获事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23666920/