我有一个名为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 a get no message box
时答案 0 :(得分:0)
如果审核了docs:
void QAbstractItemView :: doubleClicked(const QModelIndex&amp; index)
双击鼠标按钮时会发出此信号。该项目 双击鼠标是由index指定的。信号是 仅在索引有效时发出。
在您的情况下,您的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);
}