如何为组合框选择正确的列

How choose the right column for a comboBox

我有一个数据库('texpalsac'),Qtdesigner(ventas.ui),一个table(产品):

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

我希望 comboBox(comboArt) 显示第二列 ('NAME'),但我不知道该怎么做。现在只出现第一列 ('COD':111,112...)。 谢谢

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)

你必须使用QComboBoxsetModelColumn()方法来指明你要显示的列:

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

加上:

如果您想显示一个具有 2 列的 QComboBox,您必须创建一个自定义 QComboBox,如下所示:

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)

如果你想在 Qt Designer 中使用它,你必须推广它,为此你可以查看