0

Im writing an QT application, where I have 3 QComboBoxes, with a list of values. I'm trying to do so, when I select one item in a QComboBox, I will remove it from the other QComboBoxes, and when I select another or nothing, it will reappear in the other QComboBoxes again.

Do you have any ideas for this?

Edit: I have tried to use QStringList, where I had a slot, which removed it from the other QComboBoxes, but it was very bugged and often inserted 2 whitespaces and the same drink twice.

jww
  • 97,681
  • 90
  • 411
  • 885
Thisen
  • 183
  • 1
  • 9

1 Answers1

0

If all comboboxes contain the same items, then you can use the current index of one combobox to disable and hide that index of other comboboxes.

You can just subclass QComboBox and create a slot like this:

void MyComboBox::disableItem(int index)
{
    QListView *list_view = qobject_cast<QListView*>(view());
    if(list_view)
    {
        QStandardItemModel *model =  qobject_cast<QStandardItemModel*>(list_view->model());   
        list_view->setRowHidden(index, true);
        if(model)
        {
            model->item(index, 0)->setEnabled(false);
        }   
    }
}

Then you just connect the QComboBox::currentIndexChanged(int index) signal from other comboboxes to this slot. Do this for all 3 comboboxes.

You should also create a logic for enabling and showing the items again when they shouldn't be disabled. It's almost the same function as the one above. You could just create a list of indexes that should be hidden for that combobox and use that to show all the other indexes.

thuga
  • 12,601
  • 42
  • 52
  • So I tried your solution and when I change the index of one of the ComboBoxes, it crashes. I used some qDebug messages and found out the crashes happen when I try to cast ListView. First I couldn't compile and got the error "term does not evaluate to a function taking 0 arguments" and then thought the () after view was a mistake, so I tried removing them, but then it crashes. I tried changing view to QObject::sender(), but this makes it crash on QStandardItemModel conversion. – Thisen Dec 11 '14 at 13:34
  • @Thisen [`QComboBox::view`](http://doc.qt.io/qt-5/qcombobox.html#view) is a public function of `QComboBox` class. Try renaming the local variable `QListView view` to something else, like `QListView list_view`. – thuga Dec 11 '14 at 13:39