I'm using a QCombobox that is using a QTableView to display a table of data. My code is (mostly) working right now except for a few details. One of them is that when I select a row, the combo box title is updated using the first column and I would like to display data from another column. How do I change that?
I tried overriding the currentText() method but it didn't work, it seems it is not used internally to update the combo box title. Does anyone have the answer?

This is what is happening now. My data is organized in 4 columns, the 3 first are boolean values while the 4th is a string. In this screenshot, I selected the "Data 3" cell. When I select it, that gets displayed on the combobox select field is "true", the value that is present on the first column of my selected row. What I want to get is this :

I am trying to have the data from the 4th column being displayed on the combobox select field.
I found solution, but it is not the best approach. However try it, maybe it is one way to do this:
QString oldTxt;//somewhere
//...
ui->comboBox->setModel(model);
ui->comboBox->setView(new QTableView);
connect(ui->comboBox->view(),&QAbstractItemView::pressed,[=]() {
oldTxt = ui->comboBox->model()->data(ui->comboBox->view()->currentIndex()).toString();
qDebug() << ui->comboBox->model()->data(ui->comboBox->view()->currentIndex());
//ui->comboBox->setEditText(ui->comboBox->model()->data(ui->comboBox->view()->currentIndex()).toString());
});
connect(ui->comboBox,&QComboBox::currentTextChanged,[=]() {
ui->comboBox->blockSignals(true);
ui->comboBox->setCurrentText(oldTxt);
ui->comboBox->blockSignals(false);
});
Main idea: catch selected by user value and set it as current text. Second connection is necessary because without it comboBox will set another value. Just to prove that it works another code snippet:
connect(ui->comboBox->view()->selectionModel(),&QItemSelectionModel::selectionChanged,[=]() {
ui->comboBox->setCurrentText(ui->comboBox->model()->data(ui->comboBox->view()->currentIndex()).toString());
});
Result:

As you can see, it is value selected by user, not value from first column.
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.
The proper solution was the one pointed out by hank : using QComboBox::setModelColumn().
Hank, I am posting this answer because I couldn't find out how to mark your comment as the accepted answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With