Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Qt QComboBox with tableview

Tags:

c++

qt

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.

like image 406
Šerg Avatar asked Nov 25 '16 07:11

Šerg


2 Answers

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());
});
like image 148
Devopia Avatar answered Sep 20 '22 21:09

Devopia


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

like image 23
Swift - Friday Pie Avatar answered Sep 23 '22 21:09

Swift - Friday Pie