我在跟踪QMainWindow中的鼠标移动时遇到问题.我有一个切换按钮按钮生成.这是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&标签_5中应显示Y坐标以及是否启用跟踪.当关闭按钮时,应关闭鼠标跟踪并且不更新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);
在主窗口的构造函数中,您将看到鼠标事件,但您无法按下按钮,因为此中央窗口小部件根本不会收到任何鼠标事件.
解:
在Designer中设计一个小部件(带按钮和标签),覆盖它的mouseMoveEvent并用它做一个QMainWindow :: setCentralWidget.