2016-11-21 142 views
1

我想在我的QListWidget中獲取鼠標位置。當鼠標懸停在所有其他QWidgets - QMainWindowQPushButton,CentralWidget等上時,跟蹤效果良好,但QListWidget除外。當鼠標懸停在QListWidget上時,Qt鼠標跟蹤根本不起作用

C++文件:test_1.cpp

#include "test_1.h" 
#include "ui_test_1.h" 

test_1::test_1(QWidget *parent) : 
    QMainWindow(parent), 
    ui(new Ui::test_1) 
{ 
    ui->setupUi(this); 
    this->setMouseTracking(true); 
    ui->centralWidget->setMouseTracking(true); 
    ui->listWidget->setMouseTracking(true); 
    ui->pushButton->setMouseTracking(true); 


    ui->listWidget->addItem("aaa"); 
    ui->listWidget->addItem("bbb"); 
    ui->listWidget->addItem("ccc"); 
    ui->listWidget->addItem("ddd"); 
    ui->listWidget->addItem("eee"); 
} 

void test_1::mouseMoveEvent(QMouseEvent *event) 
{ 
    qDebug() << event->pos(); 
} 

test_1::~test_1() 
{ 
    delete ui; 
} 

頭文件test_1.h

#ifndef TEST_1_H 
#define TEST_1_H 

#include <QMainWindow> 
#include <QDebug> 
#include <QMouseEvent> 

namespace Ui { 
class test_1; 
} 

class test_1 : public QMainWindow 
{ 
    Q_OBJECT 

public: 
    explicit test_1(QWidget *parent = 0); 
    ~test_1(); 

private: 
    Ui::test_1 *ui; 
    void mouseMoveEvent(QMouseEvent*); 
}; 

#endif // TEST_1_H 

主:main.cpp中

#include "test_1.h" 
#include <QApplication> 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    test_1 w; 
    w.show(); 

    return a.exec(); 
} 

輸出:

QPoint(359,141) 
QPoint(358,141) 
QPoint(357,140) 
QPoint(356,140) 
QPoint(355,140) 
QPoint(354,139) 
QPoint(353,139) 
QPoint(352,139) 
QPoint(351,139) 

回答

0

解決這個以正確的方式是繼承QListWidget和實施void mouseMoveEvent(QMouseEvent *event)

但你也有另一種選擇,像installing事件過濾器上的QListWidget

在構造器中添加此:

ui->listWidget->viewport()->installEventFilter(this); 

並實現事件過濾器:

bool MainWindow::eventFilter(QObject *obj, QEvent *event) 
{ 
    if(event->type() == QEvent::MouseButtonPress) 
    { 
     qDebug() << Q_FUNC_INFO << "QEvent::MouseButtonPress"; 
    } 
    if(event->type() == QEvent::MouseMove) 
    { 
     qDebug() << Q_FUNC_INFO << " pos: " << this->mapFromGlobal(QCursor::pos()); 
    } 
    return false; 
} 
+0

不幸的是,解決方案並沒有爲我工作。我必須抓住鼠標才能在QListWidget中進行這項工作。 –

+0

你可以發佈你的解決方案作爲答案? – Tarod

1
void test_2::mouseMoveEvent(QMouseEvent *event) 
{ 
    QPoint p = event->pos(); 
    QRect widgetRect = ui->listWidget->rect(); 

    if(widgetRect.contains(p)) 
    { 
    qDebug() << "Inside"; 
    ui->listWidget->grabMouse(); 
    } 
    else 
    { 
    qDebug() << "Outside"; 
    ui->listWidget->releaseMouse(); 
    } 
} 
+0

幹得好:)快樂編碼! – Tarod