Combobox的扩展宽度

Expanding width of Combobox

我有一个Qcombobox,我想设置一个特定的宽度,它不依赖于项目宽度。我环顾四周,找到了一些仅适用于 C++ 的技巧和提示。我对那种语言一无所知!!

我先得到了什么运行:

我想先得到什么运行:

from PyQt5 import QtCore, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setLayout(QtWidgets.QVBoxLayout())
        combo = QtWidgets.QComboBox(self)
        self.layout().addWidget(combo)
        combo.addItems(["item1", "item2", "item3"])
        combo.activated[str].connect(self.onActivatedText)

    @QtCore.pyqtSlot(str)
    def onActivatedText(self, text):
        print(text)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

一个丑陋的解决方案是:

        combo.addItems(["item1     ", "item2     ", "item3     "])

minimumContentsLength : int

This property holds the minimum number of characters that should fit into the combobox.

from PyQt5 import QtCore, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        
        self.setLayout(QtWidgets.QVBoxLayout())
        
        combo = QtWidgets.QComboBox()
        
        self.layout().addWidget(combo)
        combo.addItems(["item1", "item2", "item3"])
        combo.activated[str].connect(self.onActivatedText)
        
        combo.setMinimumContentsLength(30)                 # +++

    @QtCore.pyqtSlot(str)
    def onActivatedText(self, text):
        print(text)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

您必须设置适合 QComboBox 的最小宽度:

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setLayout(QtWidgets.QVBoxLayout())
        combo = QtWidgets.QComboBox()
        self.layout().addWidget(combo)
        combo.addItems(["item1", "item2", "item3"])
        combo.setMinimumWidth(100)
        combo.activated[str].connect(self.onActivatedText)

    @QtCore.pyqtSlot(str)
    def onActivatedText(self, text):
        print(text)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

之前:

之后: