我有一个名为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进行了审查:
在您的情况下,您的QListView
没有模型,因此,单击时没有有效的QModelIndex
,因此不会发射信号。
如果要跟踪双击事件,有两种可能的解决方案:
在我的解决方案中,我将使用第二种方法:
* .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);
}
关于c++ - QListView::doubleClicked的插槽未调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50886652/