连接2个QTableWidget中的行的选择

时间:2018-11-09 18:19:04

标签: c++ qt qt5 selection qtablewidget

我正在尝试从两个QTableWidget连接行选择。 我的意思是,当我在表1中选择一行时,我希望我的程序在表2中选择同一行。这两个表没有相同的列数,因此我不能只为第一个选择一个项目并在其中选择相同的项目。第二个能力。 我尝试使用以下方法未成功:

connect(ui->table1->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), ui->table2->selectionModel(), SLOT(setCurrentIndex(QModelIndex)));

它写为:

QObject::connect: No such slot QItemSelectionModel::setCurrentIndex(QModelIndex)

你知道出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

由于setCurrentIndex()有两个参数,而不仅仅是一个参数,加上签名不匹配,导致了问题。因此,在这些情况下,您应该使用lambda并使用selectRow()

#include <QApplication>
#include <QHBoxLayout>
#include <QTableWidget>
#include <QItemSelectionModel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    auto *table1 = new QTableWidget(4, 3);
    table1->setSelectionBehavior(QAbstractItemView::SelectRows);
    auto table2 = new QTableWidget(4, 4);
    table2->setSelectionBehavior(QAbstractItemView::SelectRows);

    QObject::connect(table1->selectionModel(), &QItemSelectionModel::currentRowChanged,
                     [table2](const QModelIndex &current, const QModelIndex & previous)
    {
        if(previous.isValid())
            table2->selectRow(current.row());
    });

    QWidget w;
    auto lay = new QHBoxLayout(&w);
    lay->addWidget(table1);
    lay->addWidget(table2);
    w.show();

    return a.exec();
}