c++ - QListView::doubleClicked 的插槽未被调用

标签 c++ qt qt5 qt-signals qlistview

我有一个名为 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);
}

关于c++ - QListView::doubleClicked 的插槽未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886652/

相关文章:

c++ - 复制构造函数错误 : the object has type qualifiers that are not compatible with the member function

c++ - C++ 中 make_shared 和普通 shared_ptr 的区别

C++ Qt 返回对临时对象的引用

c++ - uint32_t 指针指向与 uint8_t 指针相同的位置

qt - 错误: expected declaration specifiers before ‘namespace’

c++ - 如何正确链接 OpenGL 着色器的开放式 GL 法线

qt - 从 C 函数向 QTextEdit 框写入文本

c++ - 需要一致的调试常量来触发所有平台上的操作

Qt 5 构造函数上的 C++ 抽象类错误

c++ - QThread 的多个实例可以引用同一个操作系统线程吗?