【问题标题】:Changing data in a QTableView depending on the selection of a QComboBox根据 QComboBox 的选择更改 QTableView 中的数据
【发布时间】:2015-01-06 19:12:57
【问题描述】:

我在QTableView 的其中一列中有一个QComboBox。如何根据我在ComboBox 中选择的内容更改其他列?我使用QComboBox 作为代表。

【问题讨论】:

  • 要创建更多信息的答案,请说您使用哪种型号? QStandardItemModel 还是您自己的自定义模型?
  • @Chernobyl:QStandardItemModel。
  • 我已经复制了您的代码(使用组合框进行委托),如果我在组合框中选择某些内容并通过输入单击确认,我的解决方案将起作用。但是,如果您想获得自动更改数据的解决方案,当您在组合框中选择另一个项目(不按 Enter)时请告诉我,我将编辑我的答案。
  • 不幸的是接下来的几个小时我将离线,但我不想给你留下我可能是半有用的答案,所以我决定也写第二种情况,它更长,更复杂但我测试了它,它有效,如果您对此有一些疑问,请告诉我。

标签: c++ qt model-view


【解决方案1】:

至少有两种方法。

  • 对 Qt 的模型 itemChanged 信号使用自然。
  • 从您的代理发出信号并在您的主窗口中捕获它。

如果你的委托是标准的,这意味着在 setModelData() 方法中你有类似的东西:

QComboBox *line = static_cast<QComboBox*>(editor);
QString data = line->currentText();
//...
model->setData(index, data);

那么我认为你应该使用自然的方式。例如:

connect(model,&QStandardItemModel::itemChanged,[=](QStandardItem * item) {
    if(item->column() == NEEDED_COLUMN)
    {
        //you found, just get data and use it as you want
        qDebug() << item->text();
    }
});

我在这里使用了C++11CONFIG += c++11.pro 文件)和new syntax of signals and slots,当然你可以根据需要使用旧语法。

我已经复制了您的代码(使用组合框进行委托),如果我在组合框中选择某些内容并通过输入点击确认,我的解决方案就可以工作。但是,如果您想获得自动更改数据的解决方案,当您在组合框中选择另一个项目(不按 Enter)时,请参阅下一个案例:

在委托上创建特殊信号:

signals:
    void boxDataChanged(const QString & str);

createEditor()方法内创建连接:

QWidget *ItemDelegate::createEditor(QWidget *parent,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &index) const
{
    QComboBox *editor = new QComboBox(parent);
    connect(editor,SIGNAL(currentIndexChanged(QString)),this,SIGNAL(boxDataChanged(QString)));
    return editor;
}

并使用它!

ItemDelegate *del = new ItemDelegate;
ui->tableView->setItemDelegate( del);
ui->tableView->setModel(model);
    connect(del,&ItemDelegate::boxDataChanged,[=](const QString & str) {
            //you found, just get data and use it as you want
            qDebug() << str;
    });

【讨论】:

  • 很好的答案!您的第一个建议对我来说很好,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2019-06-26
  • 2016-10-29
  • 2019-03-17
  • 2018-06-14
  • 1970-01-01
  • 2020-06-07
  • 2015-08-01
  • 1970-01-01
相关资源
最近更新 更多