我在跟踪 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/