【问题标题】:Trying to take a value from a dictionary of a ComboBox and instert the key in a textEdit尝试从 ComboBox 的字典中获取值并将键插入 textEdit
【发布时间】:2019-11-23 16:04:24
【问题描述】:

我有一个字典和一个显示字典值的组合框,我需要在 textEdit 中打印用户选择的字典值的键。 这是我的代码。

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow
from PyQt5.uic import loadUi
from math import pi

class MainPage(QMainWindow):

    classi = {None : None, "C25/30" : float(14.17), 
        "C28/35" : float(15.87), "C32/40" : float(18.13), 
        "C35/45" : float(19.83), "C40/50" : float(22.6),
        "C45/55" : float(25.5), "C50/60" : float(28.3)}

    Acciaio = {None : None, "B450C" : float(391.3)}

    Ferri = {14 : float(1.54), 16 : float(2.01),
         18 : float(2.54), 20 : float(3.14), 22 : float(3.8)}

    N = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    def __init__(self):
        super(MainPage, self).__init__()
        loadUi('Concrete.ui', self)
        x = self.fillCombobox()
        y = self.fillCombobox_2()
        z = self.fillCombobox_3()
        v = self.fillCombobox_4()
        w = self.fillCombobox_5()
        a = self.fillCombobox_6()
        b = self.fillCombobox_7()
        c = self.fillCombobox_8()


    def fillCombobox(self):
        for i in self.classi:
            self.comboBox.addItem(i)


    def fillCombobox_2(self):
        for i in self.Acciaio:
            self.comboBox_2.addItem(i)

    def retrieveText(self):
        x = self.comboBox.currentData()
        self.textEdit.setText(x)


app = QApplication(sys.argv)
widget = MainPage()
widget.show()
sys.exit(app.exec_())

我知道函数retrieveText 不能满足我的要求,但这是一次尝试,而且它没有提供任何输出。

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    你必须通过 itemData 保存与键关联的值,并在选择项目时获取它。

    class MainPage(QMainWindow):
    
        classi = {
            None: None,
            "C25/30": 14.17,
            "C28/35": 15.87,
            "C32/40": 18.13,
            "C35/45": 19.83,
            "C40/50": 22.6,
            "C45/55": 25.5,
            "C50/60": 28.3,
        }
    
        def __init__(self):
            super(MainPage, self).__init__()
            loadUi("Concrete.ui", self)
            self.comboBox.currentIndexChanged[int].connect(self.retrieveText)
            self.fillCombobox()
    
        def fillCombobox(self):
            for key, value in self.classi.items():
                self.comboBox.addItem(key, value)
    
        @pyqtSlot(int)
        def retrieveText(self, index):
            x = self.comboBox.itemData(index)
            if x is not None:
                self.textEdit.setText(str(x))
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      相关资源
      最近更新 更多