我以前寫測試程序的時候遇到過這樣的問題。我跟你講下我的情況,希望對你有幫助:
我的測試程序目的是要這樣的,在一個QWidget中,放置了一個QPushButton(非常大),然後在mouseMoveEvent中定義了一個矩形塊,當鼠標移動到矩形塊内部時就變換鼠標樣式,然後使用QWidget::setMouseTracking(true)。結果是,要一直按住鼠標右鍵拖動,才響應mouseMoveEvent裏邊的語句。
最後,發現一個問題,我定義的那個矩形塊是QPushButton的勢力範圍(即這個矩形塊的最頂端的是QPushButton),使用QPushButton::setMouseTracking(true) 之後,便可正常響應了。所以我覺得,因爲QPushButton是最頂端的物體,所以,mouseMoveEvent事件被QPushButton截獲了。
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- {
- // this->setMouseTracking(true);
- qDebug()<<this->hasMouseTracking();
- timer = new QTimer(this);
- timer->start(10000);
- connect(timer,SIGNAL(timeout()),this,SLOT(flashSlot()));
- btn = new QPushButton(this);
- btn->setFixedSize(QPixmap("./1.jpg").size());
- setStyleSheet("QPushButton{margin:5px;border:10px solid silver;padding:5px;"
- "background-color:gray;"
- "background-image:url(./1.jpg);"
- "background-position:top left;"
- "background-origin:content;"
- "background-repeat:none;}"
- "QPushButton:pressed {"
- "background-color: green;"
- "}");
- btn->setMouseTracking(true);
- btn->show();
- }
- void Widget::mouseMoveEvent(QMouseEvent *e)
- {
- QRect rect(0,0,300,100);
- QRect rect1(0,100,300,100);
- QRect rect2(0,200,300,100);
- if(rect.contains(e->pos()))
- {
- this->setCursor(Qt::OpenHandCursor);
- }
- else if(rect1.contains(e->pos()))
- {
- this->setCursor(Qt::ClosedHandCursor);
- }
- else if(rect2.contains(e->pos()))
- {
- this->setCursor(Qt::PointingHandCursor);
- }
- else
- {
- this->setCursor(Qt::ArrowCursor);
- }
- }