带有tableview的C++ Qt QComboBox

Šer*_*erg 6 c++ qt

我有QComboBox的问题.我需要一个带有tableview项目的组合框.

例如,QComboBox的默认值为:

???????????
?       ? ?
???????????
? index 0 ?
???????????
? index 1 ?
???????????
? index 2 ?
???????????
? index 3 ?
???????????
Run Code Online (Sandbox Code Playgroud)

我需要像这样创建ComboBox:

?????????????????????
?                 ? ?
?????????????????????
? index 0 ? index 1 ?
?????????????????????
? index 2 ? index 3 ?
?????????????????????
Run Code Online (Sandbox Code Playgroud)

我写了样本,但它无法正常工作:

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++;
}
Run Code Online (Sandbox Code Playgroud)

问题是 - 如果我选择索引3,ComboBox将设置索引2.

编辑:

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());
}
Run Code Online (Sandbox Code Playgroud)

这是工作.但我不知道它有多正确?

小智 3

您应该使用setModelColumn()因为QComboBox一次只显示一列。

像这样:

connect(table, &QTableView::pressed, [cb](const QModelIndex &index){
    cb->setModelColumn(index.column());
});
Run Code Online (Sandbox Code Playgroud)