【发布时间】:2019-09-17 12:35:57
【问题描述】:
我在QTabWidget 中有一个QTableView,每次按下按钮时,我都会在其中输入6 列的新行。在 6 列中,有 3 列设置了 QPushButton。我需要来自QTableView 的单击按钮的行号。我已将QPushButton clicked 信号连接到我的插槽clickedIndex()
这就是我试图获取单击按钮的行索引但列表为空的方式。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include <QDebug>
MainWindow::MainWindow(QWidget* parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_view = new QTableView(this);
m_model = new QStandardItemModel(m_view);
m_model->setColumnCount(6);
m_view->setModel(m_model);
m_model->insertRow(0);
QPushButton* button = new QPushButton(this);
button->setText("Click");
m_view->setIndexWidget(m_model->index(0, 2), button);
m_model->insertRow(1);
QPushButton* button1 = new QPushButton(this);
button1->setText("Click");
m_view->setIndexWidget(m_model->index(1, 3), button1);
connect(button, &QPushButton::clicked, this, &MainWindow::tableViewClicked);
connect(button1, &QPushButton::clicked, this, &MainWindow::tableViewClicked);
setCentralWidget(m_view);
}
MainWindow::~MainWindow()
{
delete ui;
}
QModelIndex MainWindow::tableViewClicked()
{
//get the list of currently selected indexes from the model
QModelIndexList indexList = m_view->selectionModel()->selectedIndexes();
if (!indexList.isEmpty())
{
qDebug() << indexList.front().row(); //prints 0 all the time
//usually the list should contain only one index at a time
return indexList.front();
}
}
这是标题:
#include <QMainWindow>
#include <QModelIndex>
#include <QTableView>
#include <QStandardItemModel>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
public slots:
QModelIndex tableViewClicked();
private:
Ui::MainWindow* ui;
QTableView* m_view;
QStandardItemModel* m_model;
};
我还尝试连接来自QTableView 的pressed 信号,但从未调用过该插槽。
connect(m_ui->tableView, &QTableView::pressed, this, &TabView::clickedIndex);
我相信如果QTableView 模型中的一个单元格上有QWidget,则永远不会调用该插槽。当我点击不带按钮的单元格时,连接有效。
我需要:
我只需要 QModelIndex 到模型中单击的按钮。
注意:我使用的是 Qt 5.7.1,我发现了一些与 selectedIndexes() 相关的错误报告,例如 this
有解决办法吗?
编辑:在我的代码中,QModelIndexList 本身是空的。
【问题讨论】:
-
我不确定,但我认为单击
QPushButton也不会选择底层行。但我可能错了。如果您想要快速而有用的答案,请考虑提供一个最小且可重现的示例。 -
@Fareanor 正如你所建议的,我已经加入了 MVCE。我也相信点击
QPushButton不会选择底层行。上面的代码一直打印 0。