gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:09 24 4
gpt4 key购买 nike

我有一个名为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com