QListView 的插槽::d ouble点击未被调用

Slot for QListView::doubleClicked not getting called

本文关键字:调用 ouble 插槽 QListView      更新时间:2023-10-16

我有一个名为listView的QListView。它是主窗口中唯一的小部件。我想跟踪列表视图上的双击。所以,我这样做了:

#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 atnColumn: " + QString :: number(index.column()) + " and Row: " + QString::number(index.row()));
}

但是当我双击列表查看没有消息框时

如果查看文档:

void QAbstractItemView::d oubleClicked(const QModelIndex &index(

双击鼠标按钮时会发出此信号。该项 鼠标被双击由索引指定。信号是 仅在索引有效时发出。

在您的情况下,您的QListView没有模型,因此当您单击时没有有效的QModelIndex,因此不会发出信号。

如果要关注双击事件,有 2 种可能的解决方案:

  • 创建 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);
}