qt – Combobox with checkboxes

Question:

It is necessary to make a combo box with checkboxes with the possibility of multiple choices. The selection of an item should occur not only by clicking on the checkbox itself, but also on the text next to it. Simply put, it is similar to the "for" tag of a label for checkboxes, for example, in html. Those. the list should not close when you click on any item from it.

Now I have a combobox with checkboxes implemented as follows:

  QComboBox *editor = new QComboBox(parent);
  QStandardItemModel *model = new QStandardItemModel(COUNT_ROWS, 1);
  for (int i = 0, sz = COUNT_ROWS; i < sz; ++i)
  {
    QStandardItem* newitem = new QStandardItem;
    newitem->setData("sometitle", Qt::EditRole);
    newitem->setData(NUMBER, Qt::UserRole);
    newitem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    newitem->setData(Qt::Unchecked, Qt::CheckStateRole);
    model->setItem(i,0,newitem);     
  }
  editor->setModel(model);

Multiple choice is present, checkboxes are displayed, text too. The problem is to catch the moment of clicking on the text in order to set the value of the corresponding checkbox.

Also, checkboxes are not shown in GNOME .

Answer:

How to get a signal to click on a combo box item (whole or text)?

The question is not very clear, or rather, what exactly do you expect. Pressing the mouse button in the drop-down list, which is on the very square of the checkbox, which is on the text, will lead to the closure of this very list and setting the selected item current. Then just bind to the corresponding signal of the list and change the state of the checkbox in the model:

void MyClass::onCurrentIndexChanged(int row) {
    const QModelIndex index = model->index(row,0);

    const Qt::CheckState check_state
        = static_cast<Qt::CheckState>(index
            .data(Qt::CheckStateRole).toInt());

    model->setData(index
        , (check_state == Qt::Checked)
            ? Qt::Unchecked : Qt::Checked
        , Qt::CheckStateRole);
}

If I put a checkbox in the first column, the text in the second, there are checkboxes, but the text next to them is not displayed

QComboBox uses a one-column model by calling QListView to showcase a list of items.

Also, checkboxes are not shown in GNOME.

Use your QListView :

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

QComboBox *cbox = new QComboBox(this);
cbox->setModel(model);
cbox->setView(view);
Scroll to Top