Creating a ComboBox in a QTableView with Pyside and Qt Designer

2.1k views Asked by At

I am using Qt Designer to manage a large UI and Pyside for the code. I'm looking to display a ComboBox in my Table.

The following answer gives a pretty detailed description of how to accomplish this when managing the UI yourself: PyQt - How to set QComboBox in a table view using QItemDelegate

My question is: How would this work when the UI is already created for me by pyside-uic? The code in the link includes, more or less:

class TableView(QtGui.QTableView):
    def __init__(self, *args, **kwargs):
        QtGui.QTableView.__init__(self, *args, **kwargs)

        # Set the delegate for column 0 of our table
        self.setItemDelegateForColumn(0, ComboDelegate(self))
[...]
class Widget(QtGui.QWidget):
    self._tm=TableModel(self)
    self._tv=TableView(self)
    self._tv.setModel(self._tm)

Does this mean that if I have a UI file, I still need to write out, then call something like the TableView object myself? Should I create a TableView in Qt Designer, then overwrite it with one I've created that inherits from QTableView and adds setItemDelegate?

Thanks in advance!

1

There are 1 answers

0
ekhumoro On

The subclass in the example is redundant, because it doesn't re-implement or add any methods. It could be re-written like this:

from PySide import QtGui, QtCore
from mainwindowui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self._model = TableModel(self)
        self._delegate = ComboDelegate(self)
        self.tableView.setModel(self._model)
        self.tableView.setItemDelegateForColumn(0, self._delegate)

Thus, the table-view is accessed as an attribute of the object that is passed to the setupUi method of the UI class generated by pyside-uic.

But what if you did need to subclass one of the classes from Qt Designer? The way to do that is to promote it to a custom class that will replace it when the python UI module is imported.

If you right-click a widget in Qt Designer and select "Promote to...", it will bring up a dialog. In the dialog, you can set a custom class name (say, "TableView"), and also set the header file to the python module it should be imported from (say, "mypkg.mainwindow"). If you then click "Promote", Qt Designer will show the classname as TableView rather than QTableView.

After re-generating the UI module, you'll then see an extra import line at the bottom of the file that looks like this:

from mypkg.mainwindow import TableView

So the custom TableView class will be used instead of a QTableView, and get all the settings from Qt Designer - plus whatever re-implemented stuff you want to add yourself.