簡體   English   中英

帶按鈕的 Python PyQt5 ComboBox

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM