[英]Changing data in a QTableView depending on the selection of a QComboBox
I have a QComboBox
in one of the columns of a QTableView
. 我在QTableView
的一列中有一个QComboBox
。 How can I change the other columns depending on what I selected in the ComboBox
? 如何根据在ComboBox
选择的内容来更改其他列? I am using the QComboBox
as a delegate. 我使用QComboBox
作为委托。
There are at least 2 approaches. 至少有两种方法。
itemChanged
signal. 对Qt的模型itemChanged
信号使用自然itemChanged
。 If your delegate is standard which means that inside setModelData()
method you have something like: 如果您的委托是标准的,则意味着在setModelData()
方法内部,您将看到以下内容:
QComboBox *line = static_cast<QComboBox*>(editor);
QString data = line->currentText();
//...
model->setData(index, data);
then I think you should use just natural way. 那么我认为您应该使用自然的方式。 For example: 例如:
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();
}
});
I used here C++11
( CONFIG += c++11
to .pro
file) and new syntax of signals and slots , but of course you can use old syntax if you want. 我在这里使用了C++11
( .pro
文件中的CONFIG += c++11
)以及信号和插槽的新语法 ,但是如果需要,您当然可以使用旧语法。
I already reproduced your code(delegate with combobox) and my solution works if I select something in combobox and confirm that by enter clicking for example. 我已经复制了您的代码(使用combobox进行代理),并且如果我在combobox中选择了某些内容并通过单击输入来确认这一点,那么我的解决方案将起作用。 But if you want to get solution where data will be changed automatically, when you select another item in combobox(without pressing enter) then see next case: 但是,如果您想获得一种解决方案,其中的数据将自动更改,那么当您在组合框中选择另一个项目(不按Enter)时,请参见下一种情况:
Create special signal onside delegate: 创建特殊的信号附加委托:
signals:
void boxDataChanged(const QString & str);
Create connection inside createEditor()
method: 在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;
}
And use it! 并使用它!
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;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.