当鼠标悬停在QListWidget上时,Qt鼠标跟踪根本不起作用

时间:2016-11-21 06:21:24

标签: c++ qt mouse

我想在QListWidget内找到鼠标位置。当鼠标悬停在除QWidgets之外的所有其他QMainWindow - QPushButtonCentralWidgetQListWidget等上时,跟踪功能正常。

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)

2 个答案:

答案 0 :(得分: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();
  }
}

答案 1 :(得分:0)

解决此问题的正确方法是继承QListWidget并实施void mouseMoveEvent(QMouseEvent *event)

但您还有另一个选项,例如QListWidget上的installing事件过滤器。

在你的构造函数中添加:

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;
}