我有一个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 "])
答案 0 :(得分:1)
您必须设置适合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_())
之前:
之后:
答案 1 :(得分:0)
minimumContentsLength:整数
此属性保存组合框中应容纳的最少字符数。
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_())