如何将 pyqt5 qcomboBox 中的文本应用于列表值
Posted
技术标签:
【中文标题】如何将 pyqt5 qcomboBox 中的文本应用于列表值【英文标题】:How to apply texts from pyqt5 qtcomboBox for lists value 【发布时间】:2021-06-26 15:00:25 【问题描述】:我从 qtcomboBox 获取文本以从列表中获取值。当我使用“if”和“elif”从列表中获取文本时是有效的。但我认为这段代码有些冗长和多余。
所以我正在尝试更改代码以使其对未来的应用程序变得简单。
我想使用代码 (1) 稍微简单地更改以下代码 (2)。但它不起作用。
(1)
def abcvalue(self):
cityyear=self.combo_text()
a1=(cityyear[0])
b1=(cityyear[1])
c1=(cityyear[2])
a=float(a1)
b=float(b1)
c=float(c1)
self.av.setText(str(a))
self.bv.setText(str(b))
self.cv.setText(str(c))
(2)
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
Calui='../_uiFiles/IDF.ui'
Toronto_2yr=[11,22,33]
Toronto_100yr=[44,55,66]
Richmondhill_2yr=[77,88,99]
Richmondhill_100yr=[10,11,12]
class MyWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self, None)
uic.loadUi(Calui, self)
self.comboBox.activated[str].connect(self.combo_text)
self.pushButton.clicked.connect(self.abcvalue)
def combo_text(self):
city = self.comboBox.currentText()
year = self.comboBox_2.currentText()
city_year=(city+year)
return city_year
def abcvalue(self):
cityyear=self.combo_text()
if cityyear=='Toronto2yr':
a1=(Toronto_2yr[0])
b1=(Toronto_2yr[1])
c1=(Toronto_2yr[2])
a=float(a1)
b=float(b1)
c=float(c1)
self.lineEdit.setText(str(a))
self.lineEdit_2.setText(str(b))
self.lineEdit_3.setText(str(c))
elif cityyear=='Toronto100yr':
a1=(Toronto_100yr[0])
b1=(Toronto_100yr[1])
c1=(Toronto_100yr[2])
a=float(a1)
b=float(b1)
c=float(c1)
self.lineEdit.setText(str(a))
self.lineEdit_2.setText(str(b))
self.lineEdit_3.setText(str(c))
elif cityyear=='Richmondhill2yr':
a1=(Richmondhill_2yr[0])
b1=(Richmondhill_2yr[1])
c1=(Richmondhill_2yr[2])
a=float(a1)
b=float(b1)
c=float(c1)
self.lineEdit.setText(str(a))
self.lineEdit_2.setText(str(b))
self.lineEdit_3.setText(str(c))
elif cityyear=='Richmondhill100yr':
a1 = (Richmondhill_100yr[0])
b1 = (Richmondhill_100yr[1])
c1 = (Richmondhill_100yr[2])
a = float(a1)
b = float(b1)
c = float(c1)
self.lineEdit.setText(str(a))
self.lineEdit_2.setText(str(b))
self.lineEdit_3.setText(str(c))
【问题讨论】:
【参考方案1】:使用这本词典
d =
"Toronto_2yr":[11,22,33],
"Toronto_100yr":[44,55,66],
"Richmondhill_2yr":[77,88,99],
"Richmondhill_100yr":[10,11,12]
并使用此功能,我希望它有效:)
def abcvalue(self):
cityyear=self.combo_text()
a1=(d[cityyear][0])
b1=(d[cityyear][1])
c1=(d[cityyear][2])
a=float(a1)
b=float(b1)
c=float(c1)
self.lineEdit.setText(str(a))
self.lineEdit_2.setText(str(b))
self.lineEdit_3.setText(str(c))
【讨论】:
以上是关于如何将 pyqt5 qcomboBox 中的文本应用于列表值的主要内容,如果未能解决你的问题,请参考以下文章
如何从 QComboBox 中获取所选项目以显示在 PyQt5 的 QTableWidget 中? (QComboBox 有复选框来选择项目)