C ++ Qt QComboBox with table view

I have a problem with QComboBox. I need a combo box with table elements.

For example, the default is QComboBox:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β–Ό β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 0 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 1 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 3 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 

I need to create a ComboBox as follows:

 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β–Ό β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 0 β”‚ index 1 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ index 2 β”‚ index 3 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ 

I wrote a sample, but it does not work correctly:

 QTableView *table = new QTableView(this); QComboBox *cb = new QComboBox; ui->verticalLayout->addWidget(cb); cb->setView(table); QStandardItemModel *model = new QStandardItemModel(2,2); cb->setModel(model); int x = 0; int y = 0; for (int i=0; i<4; i++) { model->setItem(x, y, new QStandardItem("index" + QString::number(i))); if (i == 1) { x++; y = 0; } else y++; } 

The problem is that if I select index 3, the ComboBox will set index 2.

EDIT:

 QTableView *table = new QTableView(this); QComboBox *cb = new QComboBox; ui->verticalLayout->addWidget(cb); cb->setView(table); QStandardItemModel *model = new QStandardItemModel(2,2); cb->setModel(model); for (int i=0; i<4; i++) model->setItem( i%2, i/2, new QStandardItem("index" + QString::number(i))); // This one: connect(table, SIGNAL(pressed(QModelIndex)), SLOT(setCheckBoxIndex(QModelIndex))); //--SLOT-------- void MainWindow::setCheckBoxIndex(QModelIndex index) { QComboBox* combo = qobject_cast<QComboBox*>(sender()->parent()->parent()); combo->setModelColumn(index.column()); combo->setCurrentIndex(index.row()); } 

It works.

+6
source share
2 answers

You should use setModelColumn() because the QComboBox will only show one column.

like this:

 connect(table, &QTableView::pressed, [cb](const QModelIndex &index){ cb->setModelColumn(index.column()); }); 
+2
source

Not sure if there is a reason for this loop, but in this way it is more readable and possibly error-free:

 for (int i=0; i<4; i++) { model->setItem( i%2, i/2, new QStandardItem("index" + QString::number(i))); } 

replace magic number 2 with the number of columns if it changes.

I think ComboBox uses a table row instead of an element and displays the first element that needs research. What does it do if you choose index0 or index1?

EDIT: yes, what's going on. No matter how many columns there are, the combo box gets the row (record number) from the table. I think you need to create a custom delegate for QTableView, and yes, change the Model Column. An alternative is to create an analogue of QTableView with a single-column model.

+1
source

Source: https://habr.com/ru/post/1012644/


All Articles