I have a problem with the QComboBox. I need a combobox with tableview items.
For example, the default of QComboBox is:
┌─────────┐
│ ▼ │
├─────────┤
│ index 0 │
├─────────┤
│ index 1 │
├─────────┤
│ index 2 │
├─────────┤
│ index 3 │
└─────────┘
I need create ComboBox like this:
┌───────────────────┐
│ ▼ │
├─────────┬─────────┤
│ index 0 │ index 1 │
├─────────┼─────────┤
│ index 2 │ index 3 │
└─────────┴─────────┘
I wrote the sample, but it 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 - if I choose 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's work.
You should use the setModelColumn()
because QComboBox
show only one column at time.
like this:
connect(table, &QTableView::pressed, [cb](const QModelIndex &index){
cb->setModelColumn(index.column());
});
Not sure if reason there in that loop, but this way it 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 the magic number 2 with column count, if it varies.
I think, that ComboBox uses table's line instead of item and displays first element, that requires research. What it does if you select index0 or index1 ?
EDIT: yes, that what's happening. No matter how many columns there are, combo box receives the line (record number) from table. I think that you need create a custom delegate for QTableView, and yes, change Model Column. Alternative is to create analog of QTableView with single column model
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