Search code examples
pythonpyqtpyqt5qsqltablemodel

How choose the right column for a comboBox


I have a DB ('texpalsac'), Qtdesigner(ventas.ui) ,a table (products):

 PRODUCTS 
COD   NAME
111   bag
112   shoes
121   pants
122   t-shirts

I would like that comboBox(comboArt) show the second column ('NAME') but I dont'n know how to do it. For now only the first column appears ('COD':111,112...). Thanks

class MiFormulario(QDialog, QComboBox):
    def __init__(self, parent=None):
        super(MiFormulario, self).__init__(parent)
        uic.loadUi('Venta.ui', self)

        self.model = QtSql.QSqlTableModel (self)
        self.model.setTable ("products")
        self.model.select ()
        self.comboArt.setModel (self.model)

Solution

  • You have to use the setModelColumn() method of QComboBox to indicate the column you want to display:

    class MiFormulario(QDialog): # <-- remove QComboBox, it is unnecessary
        def __init__(self, parent=None):
            super(MiFormulario, self).__init__(parent)
            uic.loadUi('Venta.ui', self)
    
            self.model = QtSql.QSqlTableModel(self)
            self.model.setTable("products")
            self.model.select()
            self.comboArt.setModel(self.model)
            self.comboArt.setModelColumn(1) # <--- select column 1
    

    Plus:

    If you want to show a QComboBox with 2 columns you must create a custom QComboBox like the one shown below:

    multicombobox.py

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class CustomView(QtWidgets.QTableView):
        def __init__(self, parent=None):
            super(CustomView, self).__init__(parent)
            self.verticalHeader().hide()
            self.horizontalHeader().hide()
            self.setShowGrid(False)
            self.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
            self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
            self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
    
        def adjustWidth(self):
            w = sum([self.horizontalHeader().sectionSize(i) for i in range(self.horizontalHeader().count())])
            self.setFixedWidth(w)
            self.parentWidget().setFixedWidth(w)
    
        def showEvent(self, e):
            if self.isVisible():
                self.adjustWidth()
            super(CustomView, self).showEvent(e)
    
    class MultiComboBox(QtWidgets.QComboBox):
        def setModel(self, model):
            super(MultiComboBox, self).setModel(model)
            view = CustomView(self)
            self.setView(view)
    
        def paintEvent(self, e):
            painter = QtWidgets.QStylePainter(self)
            painter.setPen(self.palette().color(QtGui.QPalette.Text))
            opt = QtWidgets.QStyleOptionComboBox()
            self.initStyleOption(opt)
            if self.model():
                p = self.rootModelIndex()
                t = ""
                for c in range(self.model().columnCount(p)):
                    t += " " + self.model().index(self.currentIndex(), c).data()
                opt.currentText = t
                fm = QtGui.QFontMetrics(self.font())
                self.setMinimumWidth(fm.width(t))
            painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, opt)
            painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, opt)
    

    And if you want to use it in Qt Designer you must promote it, for this you can review this answer.