Adding QComboBox to a QTableView and getting/setting values after creation

Heads up! You've already completed this tutorial.

Amit_Khanna | 2021-04-12 15:41:56 UTC | #1

Hi there,

My first post here :) I have been following the book which is very informative but I wasn't able to find a few things with MVC, especially QTableView. I would like to know how to add a QComboBox and then setting/getting its values after its created.

I managed to add the combo box with QItemDelegate but now I am not sure once it's added, how can I access it and change the items in the combo box. I mainly want to display values and once a value is selected, later get this selected value to use it in another function.

I managed to change the value too with adding a function in delegate to update the data but now this data is displayed in all combo boxes of the cell. My combo box shows versions so each row needs to show different versions in the combo box!

Any guidance or example is appreciated!

Thanks, ak

The complete guide to packaging Python GUI applications with PyInstaller.
[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]


Amit_Khanna | 2021-04-15 20:45:02 UTC | #3

Adding corrected code:

python
class ComboDelegate(QItemDelegate):
    """
    A delegate to add QComboBox in every cell of the given column
    """

    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

    def createEditor(self, parent, option, index):
        combobox = QComboBox(parent)
        version_list = []
        for item in index.data():
            if item not in version_list:
                version_list.append(item)

        combobox.addItems(version_list)
        combobox.currentTextChanged.connect(lambda value: self.currentIndexChanged(index, value))
        return combobox

    def setEditorData(self, editor, index):
        value = index.data()
        if value:
            maxval = len(value)
            editor.setCurrentIndex(maxval - 1)

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

Adding QComboBox to a QTableView and getting/setting values after creation was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt.