【问题标题】:Connecting selection of row in 2 QTableWidget连接2 QTableWidget中的行选择
【发布时间】:2019-04-13 08:29:00
【问题描述】:

我正在尝试连接来自两个 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)

你知道出了什么问题吗?

【问题讨论】:

    标签: c++ qt qt5 selection qtablewidget


    【解决方案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();
    }
    

    【讨论】:

    • 亲爱的eyllanesc,感谢您的回答。我试图使您的代码适应我的代码但没有成功。我在 lambda 捕获列表中收到编译错误:预期的 ',' 或 ']'。我做了以下事情:
    • QObject::connect(ui->table1->selectionModel(), &QItemSelectionModel::currentRowChanged, [ui->table2](const QModelIndex &current, const QModelIndex & previous) { if(previous.isValid ()){ QItemSelectionModel::SelectionFlags command = QItemSelectionModel::Rows | QItemSelectionModel::ClearAndSelect; ui->table2->selectionModel()->setCurrentIndex(current, command); } });
    • @froz 将 [ui-&gt;table2] 更改为 [this]
    • 谢谢,它正在工作 :) 但是,最后一件事,我有时在终端中有以下内容:qt.accessibility.core: Cannot create accessible child interface for object: QTableWidget(0x5593ad844f30, name = "table2") index: 23
    • @froz 这很奇怪,我没有那个消息,可能是 Qt 的版本或编译(或你的项目的编译)引起的。如果我的回答对你有帮助,别忘了标记为正确,如果你不知道怎么做,请查看tour,这是最好的感谢方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2018-01-16
    相关资源
    最近更新 更多