c++ - QMainWindow 不使用 setMouseTracking() 跟踪鼠标

标签 c++ qt

我在跟踪 QMainWindow 中的鼠标移动时遇到问题。我有一个切换按钮 buttonGenerate。这是 MainWindow

的代码
class MainWindow : public QMainWindow, private Ui::MainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

protected:
    void mouseMoveEvent(QMouseEvent *);

private slots:
    void on_buttonGenerate_toggled(bool checked);
};

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    label_5->setText(tr("%1 %2 %3")
                     .arg(event->x())
                     .arg(event->y())
                     .arg(hasMouseTracking()));

    event->ignore();
}

void MainWindow::on_buttonGenerate_toggled(bool checked)
{
    buttonGenerate->setText(checked
                            ? tr("Stop")
                            : tr("Start"));
    setMouseTracking(checked);
}

当按钮打开时,鼠标应该被跟踪,它的 X 和 Y 坐标以及是否启用跟踪应该显示在 label_5 中。当按钮关闭时,鼠标跟踪应该关闭并且 label_5 不会更新。事实并非如此。

无论按钮是否按下,鼠标都不会被跟踪。只有当我按住鼠标按钮时,label_5 才会更新,这与 setMouseTracking(bool) 是否处于事件状态无关。

如有任何见解,我们将不胜感激。

最佳答案

发生这种情况是因为 Qt 设计器在 QMainWindow 中创建了一个“隐藏”的小部件,如生成的 ui_MainWindow.h 所示:

[...]
centralWidget = new QWidget(MainWindow);
[...]
MainWindow->setCentralWidget(centralWidget);

因此,正是这个小部件接收鼠标事件并在其上放置子小部件,而不是 QMainWindow。

如果你放置:

centralWidget()->setAttribute(Qt::WA_TransparentForMouseEvents);
setMouseTracking(true);

在主窗口的构造函数中,您会看到鼠标事件,但您无法按下按钮,因为这个中央小部件根本不接收任何鼠标事件。

解决方法:

在设计器中设计一个小部件(带有按钮和标签),覆盖它的 mouseMoveEvent 并使用它执行 QMainWindow::setCentralWidget

关于c++ - QMainWindow 不使用 setMouseTracking() 跟踪鼠标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638420/

相关文章:

c++ - 关于通过 Get 和 Set 方法传递字符串

C++ - 纯虚函数的参数

c++ - 使用 MSVC2010 在动态 QT 中使用 RegOpenKey 和 RegEnumKey

android - dlopen 失败 : cannot locate symbol "__cxa_finalize" referenced by "/system/lib/libdl.so"

c++ - 共享库加载时静态变量损坏

c++ - 为什么++(后增量运算符)不能是左值?

c++ - 在 C++ 中的模板中定义类的新对象,错误 : Missing Template Arguments

c++ - 如何在 XWindows 中获取装饰窗口的内部尺寸?

c++ - 在 Linux 上使用 Qt 的限定名无效

windows - Hello World 没有输出 - Qt SDK 2010 - Mingw (gcc 4.6.3) - WindowsXP