setSizeHint() 不适用于更改 QListWidget 中 QListWidgetItem 的高度

setSizeHint() not working for changing the height of QListWidgetItem in QListWidget

这是我更改列表中项目高度的代码

ui.symbolsList.insertItem(ui.symbolsList.count(), ui.addSymbolText.text())
count = ui.symbolsList.count()
for i in range(count):
    item = ui.symbolsList.item(i)
    item.setSizeHint(QSize(item.sizeHint().width(), 60))

这不会更改 QListWidget 中项目的高度。我还尝试先创建具有自定义高度的项目,然后将该项目添加到列表中。 我还需要做什么?

以下是工作代码:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QSize


class Ui_MainWindow(object):
    def submit(self):
        self.listWidget.insertItem(self.listWidget.count(), self.lineEdit.text())
        count = self.listWidget.count()
        for i in range(count):
            item = self.listWidget.item(i)
            item.setSizeHint(QSize(item.sizeHint().width(), 60))
                
        self.lineEdit.setText("")

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(170, 110, 256, 192))
        self.listWidget.setObjectName("listWidget")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(170, 70, 113, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(300, 70, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
    
        self.pushButton.clicked.connect(self.submit)
    
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
    
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

问题是默认的 sizeHint() 是 QSize(-1, -1),这是无效的,所以当创建一个宽度为 -1 的新 QSize 时,它​​会变得无效,导致在绘制项目时不使用它。解决办法不是使用默认的sizeHint()的宽度而是将宽度设置为0:

item.setSizeHint(QSize(0, 60))