前言:
根据官方文档的描述可知–如果一个控件的QtCore.Qt.WA_NoMousePropagation的属性设为True,则不会将事件传递给父窗口控件。调用setAttribute( )方法可修改此参数:
setAttribute (QtCore.Qt.WA_NoMousePropagation, True)
可是根据操作的话,针对QPushButton 好像并不起作用,欢迎讨论
我列出Demo代码
(1)测试
.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow() override;
protected:
void mouseMoveEvent(QMouseEvent *event) override;
};
#endif // MAINWINDOW_H
.cpp文件
#include "mainwindow.h"
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
this->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
this->setFixedSize(500, 500);
QWidget *wg1 = new QWidget(this);
wg1->setFixedSize(300, 300);
wg1->setStyleSheet("background-color:black;");
QWidget *wg2 = new QWidget(wg1);
wg2->setFixedSize(100, 100);
wg2->setStyleSheet("background-color:red;");
// wg2->setAttribute(Qt::WA_NoMousePropagation);
QHBoxLayout *m_layout = new QHBoxLayout;
wg2->setLayout(m_layout);
QPushButton *m_btn1 = new QPushButton(wg2);
m_layout->addWidget(m_btn1);
m_btn1->setText("--btn1--");
m_btn1->setAttribute(Qt::WA_NoMousePropagation, false);
QLabel *m_label = new QLabel(wg2);
m_label->setFixedSize(20, 100);
m_layout->addWidget(m_label);
m_label->setStyleSheet("background-color:pink");
setMouseTracking(true);
wg1->setMouseTracking(true);
wg2->setMouseTracking(true);
}
MainWindow::~MainWindow()
{
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
QPoint p_ab = event->globalPos();
QPoint p_re = event->pos();
QString str;
str = QString("%1 , %2").arg(p_ab.x()).arg(p_ab.y());
qInfo() << str;
// str = QString("%1 , %2").arg(p_re.x()).arg(p_re.y());
// ui.edit_m_relative->setText(str);
}
(2)其他资料
由搜到的一篇个人博客指出,也是针对Qwidget 操作了相关试验
如下:
列印出的資訊為: b = 0為此,我們知道,預設情況WA_NoMousePropagation為0,表示會把滑鼠訊息發給父視窗
如果把WA_NoMousePropagation設定為1, 則不會把滑鼠訊息發給父親視窗了.編譯執行,我們可以看出:
1)當滑鼠移動到子視窗MyChildWidget時,沒有Hover的滑鼠訊息了
2)當滑鼠點選在子視窗MyChildWidget時,也無法拖動.
這充分說明,MyChildWidget沒有把滑鼠訊息發給父親視窗MoveableWidget
也没有具体列出QpushBtton 设置的作用及应用场景,网上诸多博文都是使用到了QpushButton,因此我才关注了该问题,有懂的大佬希望能够留言解释,谢谢。本人也将持续更新,补充到该篇博文。
参考
1.QT滑鼠訊息分析