[英]Python PyQt5 ComboBox with button
我尝试制作一个包含 3 个项目的组合框。首先,用户将选择其中一个并按下“选择”按钮,然后在它们附近的文本框中说“苹果是红色”或“香蕉是黄色”等..但我无法连接按钮和组合框。我知道应该有 .clicked 和 .activated 等,但我不知道如何将它们用于这个程序?
self.button = QPushButton("Select")
self.text = QLineEdit()
self.combo = QComboBox(self)
self.combo.additem("Select one...")
self.combo.additem("Apple")
self.combo.additem("Orange")
self.combo.additem("Banana")
v_box = QVBoxLayout()
v_box.addWidget(self.button)
v_box.addStrecth()
v_box.addWidget(self.combo)
h_box = QHBoxLayout()
h_box.addLayout(v_box)
h_box.addWidget(text)
self.setLayout(h_box)
self.show()
def banana():
print("BANANA IS YELLOW")
def apple():
print("APPLE IS RED")
def orange():
print("ORANGE IS ORANGE")
尝试一下:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.Qt import *
class Widget(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.button = QPushButton("Select")
self.button.clicked.connect(self.on_clicled) # +++
self.lineEdit = QLineEdit()
self.current_text = None # +++
self.combo = QComboBox(self)
self.combo.addItems(["Select one...", "Apple", "Orange", "Banana"])
self.combo.currentTextChanged.connect(self.on_combobox_func) # +++
v_box = QVBoxLayout()
v_box.addWidget(self.button)
v_box.addStretch()
v_box.addWidget(self.combo)
h_box = QHBoxLayout(self)
h_box.addLayout(v_box)
h_box.addWidget(self.lineEdit)
def on_combobox_func(self, text): # +++
self.current_text = text
def on_clicled(self): # +++
if self.current_text == "Apple":
print("APPLE IS RED")
self.lineEdit.setText("APPLE IS RED")
elif self.current_text == "Orange":
print("ORANGE IS ORANGE")
self.lineEdit.setText("ORANGE IS ORANGE")
elif self.current_text == "Banana":
print("BANANA IS YELLOW")
self.lineEdit.setText("BANANA IS YELLOW")
else: self.lineEdit.setText("Select one...")
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = Widget()
demo.show()
sys.exit(app.exec_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.