Как использовать QItemSelectionModel для QComboBox? - PullRequest
0 голосов
/ 06 июня 2019

Как использовать QItemSelectionModel для QComboBox?

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 Ответ

1 голос
/ 06 июня 2019

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);
});
...