C++ SelectedIndex()返回的QModelIndexList始终为空
我在C++ SelectedIndex()返回的QModelIndexList始终为空,c++,qt,c++11,C++,Qt,C++11,我在qtablewidget中有一个QTableView,每次按下按钮,我都会在其中输入一个包含6列的新行。在6列中,有3列设置了QPushButton。我需要QTableView中单击按钮的行号。我已将QPushButtonclicked信号连接到我的插槽clickedIndex() 这就是我试图获取单击按钮的行索引的方式,但是列表是空的 #include "mainwindow.h" #include "ui_mainwindow.h" #include <QPushButton>
qtablewidget
中有一个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();
}
}
我相信如果在QTableView
模型中的一个单元格上有QWidget
,则永远不会调用插槽。当我点击没有按钮的单元格时,连接就起作用了
我需要:
我只需要将QModelIndex
添加到模型中单击的按钮
注意:我正在使用Qt5.7.1,我发现了一些与selectedIndex()相关的错误报告,如
有解决办法吗
编辑:在我的代码中,QModelIndexList
本身是空的。您可以从表视图中获得“单击”信号。
要获取索引,可以使用以下代码:
connect(m_ui->tableView, SIGNAL(clicked(QModelIndex)), this,
SLOT(slotClicked(QModelIndex)));
头文件中的插槽:
void slotCLicked(const QModelIndex &index);
void XY::slotClicked(const QModelIndex &index)
{
qDebug() << index;
}
void slotclick(常数QModelIndex&index);
void XY::slotClicked(常数QModelIndex和索引)
{
qDebug()这是一种做你想做的事情的方法
connect(button, &QPushButton::clicked, this, [this, button, view] {
qDebug() << view->indexAt(button->pos()).row();
});
connect(按钮,&QPushButton::单击,此,[此,按钮,视图]{
qDebug()索引(按钮->位置()).row();
});
< /代码>我不确定,但我不认为点击<代码> QPushButton < /代码>也会选择基础行。但是我可能错了。如果你想要快速有用的答案,请考虑提供一个最小的和可重复的例子。“费拉诺,正如你所说的,我已经提出了一个MVCE。我还相信点击<代码> QPushButton <代码>将不会。t选择基础行。上面的代码始终打印0。按下
和单击
仅对不包含小部件的单元格有效。这不适用于我。
void slotCLicked(const QModelIndex &index);
void XY::slotClicked(const QModelIndex &index)
{
qDebug() << index;
}
connect(button, &QPushButton::clicked, this, [this, button, view] {
qDebug() << view->indexAt(button->pos()).row();
});