面试题答案
一键面试实现思路
- 界面搭建:使用PyQt相关的布局管理器和控件类,创建包含多个文本框和下拉框的表单界面。
- 信号连接:为下拉框的
currentIndexChanged
信号连接一个槽函数。当下拉框选项改变时,槽函数被触发。 - 获取文本框值:在槽函数中获取各个文本框的输入值。
- 条件判断:使用
if
语句根据不同的文本框值组合,执行相应的操作,如计算数值或显示特定提示。
关键代码示例
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QLineEdit, QLabel
class Form(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
self.comboBox = QComboBox()
self.comboBox.addItems(['选项1', '特定选项', '选项3'])
self.comboBox.currentIndexChanged.connect(self.handleComboBoxChange)
self.lineEdit1 = QLineEdit()
self.lineEdit2 = QLineEdit()
self.resultLabel = QLabel()
layout.addWidget(self.comboBox)
layout.addWidget(self.lineEdit1)
layout.addWidget(self.lineEdit2)
layout.addWidget(self.resultLabel)
self.setLayout(layout)
def handleComboBoxChange(self, index):
if self.comboBox.currentText() == '特定选项':
text1 = self.lineEdit1.text()
text2 = self.lineEdit2.text()
try:
num1 = float(text1)
num2 = float(text2)
result = num1 + num2
self.resultLabel.setText(f"计算结果: {result}")
except ValueError:
self.resultLabel.setText("请输入有效的数字")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Form()
ex.show()
sys.exit(app.exec_())
上述代码创建了一个包含一个下拉框、两个文本框和一个标签的简单表单界面。当下拉框选择“特定选项”时,获取两个文本框的值并尝试相加,若输入不是有效的数字则显示提示。