我在跟踪鼠标移动时遇到问题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);
}
Run Code Online (Sandbox Code Playgroud)
当按钮打开时,应跟踪鼠标,并且应显示其X和Y坐标以及是否启用跟踪label_5.当关闭按钮时,应关闭鼠标跟踪并且不更新label_5.不是这种情况.
无论是否按下按钮,都不会跟踪鼠标.只有当我按住鼠标按钮时才会label_5更新,这无论是否setMouseTracking(bool)处于活动状态.
任何见解将不胜感激.
Chr*_*wet 15
它发生是因为Qt设计器创建了一个"隐藏"小部件QMainWindow,如生成中所示ui_MainWindow.h:
[...]
centralWidget = new QWidget(MainWindow);
[...]
MainWindow->setCentralWidget(centralWidget);
Run Code Online (Sandbox Code Playgroud)
因此,这个小部件接收鼠标事件并放置子窗口小部件,而不是QMainWindow.
如果你放置:
centralWidget()->setAttribute(Qt::WA_TransparentForMouseEvents);
setMouseTracking(true);
Run Code Online (Sandbox Code Playgroud)
在主窗口的构造函数中,您将看到鼠标事件,但您无法按下按钮,因为此中央窗口小部件根本不会收到任何鼠标事件.
解:
在Designer中设计一个小部件(带按钮和标签),覆盖它mouseMoveEvent并QMainWindow::setCentralWidget用它做一个.