简体   繁体   中英

Python PyQt5 ComboBox with button

I try to make a combobox who has 3 item.First of all user is gonna chose one of them and push the button "Select" and then in the text box near them say like "Apple is red" or "Banana is yellow" etc..But i couldnt connect button and combobox.I know there should be .clicked and .activated etc. but I dont know how to use them for this program?



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")


Try it:

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_())

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM