c++ - Qt mouseReleaseEvent() 没有触发?

标签 c++ qt qt5 qmouseevent

我有一个显示图片的库,我们称它为 PictureGLWidget,其中:

class PictureGLWidget: public QGLWidget {

因此 PictureGLWidget 扩展了 QGLWidget。在PictureGlWidget中

  void PictureGlWidget::mouseReleaseEvent(QMouseEvent* releaseEvent);

已经实现。

我开始了一个自己的项目,假设是 MyMainWindow 类,我只使用 PictureGlWidget 作为指针对象:

PictureGlWidget * myPictureGLWidget = new PictureGlWidget(...);
//..
layout->addWidget(myPictureGLWidget , 0, 1);

此时,我已经可以在我的 MainwindowWidget 中看到 PictureGlWidget 和相应的图片。当我单击那个 PictureGlWidget 时,按住鼠标,我可以移动图片(如 2D 滚动),因为它比我的小主窗口大得多。

进一步对PictureGlWidget提供了一个功能

bool PictureGlWidget::getPictureLocation(double& xPos, double& yPos);

它只是告诉我图片的中心位置,我在那里释放了图片的当前剪辑。请记住,我的图片比我的小 MainWindowWidget 大得多,因此比我的 PictureGLWidget 大得多。假设图片有 4000x4000px(0,0 左上角)。 PictureGLWidget 仅用于显示 800x800px。所以 getPictureLocation() 设置了当前显示图片部分的中心坐标,它会返回类似 (400, 400) 的内容,它可能位于左上角中间的某个位置。

我想捕获当前显示的图片部分(只是那张大图片的一小部分)中心位置,在那个小部件中滚动并释放鼠标后。我以为我是通过覆盖

MyMainWindow::mouseReleaseEvent(QMouseEvent *event){ qDebug() << "Mouse released!"; }

方法,但尚未将其连接到任何地方。目前它没有对我的 mouseReleases 使用react,也没有显示该文本。

最佳答案

QWidget 中的虚拟保护方法,您可以重写以对某些事件使用react,不需要“连接”。这些不是 Qt 槽,而是 Qt 在必要时自动调用的经典函数。

Qt Event system doc 中所述,如果实现 PictureGlWidget::mouseReleaseEvent(QMouseEvent*) 接受事件,它不会传播到父窗口部件。但是您可以为 PictureGLWidget 安装一个事件过滤器,并在事件发送给它之前接收事件。

PictureGlWidget * myPictureGLWidget = new PictureGlWidget(...);
layout->addWidget(myPictureGLWidget , 0, 1);
myPictureGLWidget->installEventFilter(this);

然后在主窗口中实现正确的方法:

bool MyMainWindow::eventFilter(QObject *object, QEvent *event)
{
    if (object == myPictureGLWidget && event->type() == QEvent::MouseButtonRelease) {
        QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
        // Do what you need here
    }
    // The event will be correctly sent to the widget
    return false;
    // If you want to stop the event propagation now:
    // return true
}

您甚至可以决定,在完成您必须做的事情后,是要停止事件,还是将其发送到 PictureQLWidget 实例(正常行为)。

文档:

关于c++ - Qt mouseReleaseEvent() 没有触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31517566/

相关文章:

c++ - 如何将 Twitter 与 C++ 应用程序集成?

c++ - 在 mousePressEvent() 中更改 QWidget 父级不起作用

c++ - 使用cmake将两种解决方案合二为一

python - 当 PyQt4 中的 QRunners 的 QThreadPool 执行完成时得到通知

c++ - Windows 上的 KDE 框架部署

C++ 迭代器从 typedef std::map 声明为模板参数

c++ - 'CREATE' 附近偏移量 8 处的 RedisGraph 语法错误

c++ - 为什么使用自定义对话框会得到 "QMetaObject::connectSlotsByName: No matching signal"?

c++ - cplusplus.com 错了吗?指针和字符串文字

qt - 如何在 Qt TableView 中实现类似过滤的电子表格?