QListView::doubleClicked 的插槽未被调用

Slot for QListView::doubleClicked not getting called

我有一个名为 listView 的 QListView。它是 MainWindow 中唯一的小部件。我想跟踪 listView 上的双击。所以,我这样做了:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    listView = new QListView(this);

    this->setCentralWidget(listView);

    connect(listView, &QListView::doubleClicked, this, &MainWindow::onDoubleClicked);
}

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

void MainWindow :: onDoubleClicked(const QModelIndex &index)
{
    QMessageBox :: information(this, "Info", "List view was double clicked at\nColumn: " + QString :: number(index.column()) + " and Row: " + QString::number(index.row()));
}

但是当我双击 listView 时没有消息框

如果 docs 被审查:

void QAbstractItemView::doubleClicked(const QModelIndex &index)

This signal is emitted when a mouse button is double-clicked. The item the mouse was double-clicked on is specified by index. The signal is only emitted when the index is valid.

在你的情况下,你的QListView没有模型,所以当你点击时没有有效的QModelIndex,所以信号不会发出。

如果您想跟随双击事件,有两种可能的解决方案:

  • 创建一个 QListView 并覆盖 mouseDoubleClickEvent 事件。
  • 或者使用事件过滤器。

在我的解决方案中,我将使用第二种方法:

*.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class QListView;

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    bool eventFilter(QObject *watched, QEvent *event);

private:
    Ui::MainWindow *ui;
    QListView *listView;
};


#endif // MAINWINDOW_H

*.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QEvent>
#include <QListView>
#include <QMouseEvent>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    listView = new QListView;
    this->setCentralWidget(listView);

    listView->viewport()->installEventFilter(this);
}

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

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == listView->viewport() && event->type() == QEvent::MouseButtonDblClick){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        qDebug()<<"MouseButtonDblClick"<<mouseEvent->pos();
    }
    return QMainWindow::eventFilter(watched, event);
}