如何为QComboBox使用QItemSelectionModel?

时间:2019-06-06 15:16:20

标签: c++ qt qt5

如何对QComboBox使用QItemSelectionModel?

BaseModel *baseModel = new BaseModel(data, this);
QItemSelectionModel baseModelSelected(baseModel);
ui->tableView->setModel(baseModel);
ui->comboBox->setModel(baseModel);
ui->tableView->setSelectionModel(baseModelSelected);
ui->comboBox->setSelectionModel(baseModelSelected); // can't

1 个答案:

答案 0 :(得分:1)

QComboBox不允许您共享选择模型。但是,当用户在列表中选择新项目时,可以使用视图的选择模型来更新组合框。

例如:

QStringListModel* model = new QStringListModel(QStringList() << "Op1" << "Opt2" << "Opt3" << "Opt4");

QListView* view = new QListView();
view->setModel(model);

QComboBox* combobox = new QComboBox();
combobox->setMinimumWidth(200);
combobox->setModel(model);

QWidget* w = new QWidget();
QHBoxLayout* layout = new QHBoxLayout(w);
layout->addWidget(view);
layout->addWidget(combobox);

QObject::connect(view->selectionModel(), &QItemSelectionModel::selectionChanged, [=](
                 QItemSelection const& newSelection, QItemSelection const& previousSelection) {
    if (newSelection.isEmpty())
        return; // No selected item in the view. Do nothing

    // First selected item
    QString const item = newSelection.indexes().first().data().toString();
    combobox->setCurrentText(item);
});
相关问题