Redefined the standard view of a QComboBox in this example:

// создаем и настраиваем модель QStandardItemModel *model = new QStandardItemModel; model->setItem(0, 0, new QStandardItem("111")); model->setItem(0, 1, new QStandardItem("Name 1")); model->setItem(1, 0, new QStandardItem("222")); model->setItem(1, 1, new QStandardItem("Name 2")); // создаем и настраиваем view QTableView *coilView = new QTableView(this); coilView->setSelectionBehavior(QAbstractItemView::SelectRows); coilView->horizontalHeader()->setStretchLastSection(true); coilView->verticalHeader()->setStretchLastSection(true); coilView->verticalHeader()->hide(); coilView->horizontalHeader()->hide(); coilView->setColumnWidth(0, 50); ui->comboBox->setView(coilView); ui->comboBox->setModel(model); // присоединяю слот для обработки textChanged connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(textChanged(int))); 

As a result, in the drop-down list I get the following: combobox sample

By default, the value in the combo box is set by the first column (i.e., by code). And I need to make it so that in the collapsed combobox the name is displayed, not the code.

I tried to make the currentIndexChanged(int index) signal:

 void MainWindow::textChanged(int index) { QStandardItemModel *model = qobject_cast<QStandardItemModel*>(ui->comboBox->model()); QString name = model->item(index, 1)->text(); QLineEdit *line = ui->comboBox->lineEdit(); qDebug() << name; // ОК! в выводе приложения вижу корректное имя line->setText(name); // и тут программа падает.... } 

How to correctly change the line that is written in LineEdit?

  • Apparently the combobox is not editable, which means that ui->comboBox->lineEdit(); returns 0 and then crash when trying to call setText for a null object. - αλεχολυτ
  • @ älёxölüt, the way it is ... but making editable, as for me, is not entirely appropriate (after all, codes and names come from the database) - Bogdan

1 answer 1

 ui->comboBox->setModelColumn(1); 

see QComboBox :: modelColumn