如何从qcombobox获取itemdata?

2024-04-26 11:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,当我点击在一个qtwidts.QPushButton显示来自qtwidkets.QComboBox文件. 我用以下代码填充组合框:

self.comboBox.addItem("Sandro",1)
self.comboBox.addItem("Daniel",2)
self.comboBox.addItem("Pedro",3)

它填满了整个世界qtwidkets.QComboBox文件,但是当我设置qtwidts.QPushButton. 我在setupUi中添加了以下内容:

self.pushButton.clicked.connect(self.showId)

最后开发了showId函数:

id_us = self.comboBox.itemData(self.comboBox.currentIndex())
print('VAL ',id_us)

当我点击我的按钮,窗口关闭,是什么问题? 我共享我的所有代码访问窗体.py地址:

# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(598, 245)
        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 20, 541, 201))
        self.groupBox.setObjectName("groupBox")
        self.pushButton = QtWidgets.QPushButton(self.groupBox)
        self.pushButton.setGeometry(QtCore.QRect(50, 150, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.groupBox)
        self.label.setGeometry(QtCore.QRect(40, 30, 47, 13))
        self.label.setObjectName("label")
        self.comboBox = QtWidgets.QComboBox(self.groupBox)
        self.comboBox.setGeometry(QtCore.QRect(110, 30, 111, 22))
        self.comboBox.setObjectName("comboBox")
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        self.fillCombo()
        self.pushButton.clicked.connect(self.showId)
    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.groupBox.setTitle(_translate("Form", "Datos"))
        self.pushButton.setText(_translate("Form", "Inicio"))
        self.label.setText(_translate("Form", "TextLabel"))
    def showId(self):
        id_us = self.comboBox.itemData(self.comboBox.currentIndex()).toPyObject()
        print('VAL ',id_us)
    def fillCombo(self):
        self.comboBox.addItem("Sandro",1)
        self.comboBox.addItem("Daniel",2)
        self.comboBox.addItem("Pedro",3)
if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

提前谢谢。你知道吗


Tags: selfformiddeflabeltranslateusqtcore
1条回答
网友
1楼 · 发布于 2024-04-26 11:56:08

在我看来,您使用的是过时的教程,在PyQt4中,您必须使用toPyObject()方法将PyQt对象转换为python本机对象,但在PyQt5中,不再需要:

def showId(self):
    id_us = self.comboBox.itemData(self.comboBox.currentIndex()) # .toPyObject()
    print('VAL ',id_us)

建议使用terminal或CMD来获取错误消息,因为ide在处理PyQt错误消息方面存在问题。你知道吗

相关问题 更多 >