Adding No to QComboBox Model Related

I have a QComboBox, so the user can name the network name from the model column. I am using code like this:

self.networkSelectionCombo = QtGui.QComboBox() self.networkSelectionCombo.setModel(self.model.worldLinks) self.networkSelectionCombo.setModelColumn(WLM.NET_NAME) 

I am using PySide, but this is a Qt question. Answers using C ++ are fine.

I need to give the user the option not to select any network. I would like to add an additional item to the No combo box. However, this is simply overridden by the contents of the model.

The only way I can think of is to create an intermediate user view in this column of the model and use it to update combos, then the view can handle the addition of an additional "magic" element. Does anyone know a more elegant way to do this?

+4
source share
1 answer

One possible solution is to subclass the model that you use to add an extra element there. The implementation is straightforward. If you name your model MyModel , then the subclass will look like this (C ++):

 class MyModelWithNoneEntry : public MyModel { public: int rowCount() {return MyModel::rowCount()+1;} int columnCount() {return MyModel::columnCOunt();} QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const { if (index.row() == 0) { // if we are at the desired column return the None item if (index.column() == NET_NAME && role == Qt::DisplayRole) return QVariant("None"); // otherwise a non valid QVariant else return QVariant(); } // Return the parent data else return MyModel::data(createIndex(index.row()-1,index.col()), role); } // parent and index should be defined as well but their implementation is straight // forward } 

Now you can set this model in the combo box.

+3
source

Source: https://habr.com/ru/post/1402260/


All Articles