[Python] How to return combobox item to main window when item is selected

Discussão em 'Python' iniciado por Stack, Maio 2, 2025.

  1. Stack

    Stack Membro Participativo

    New to Qt. I'm trying to create a general purpose ComboBox that can be used in multiple situations. This code works when the Save button is pressed. However I would like to dispense with the save button and have the combobox selected item returned to the main window when the item is selected. I have been unable to figure this out and none of the examples I've seen help. Grateful for any suggestions.

    from PyQt5 import QtCore, QtGui, QtWidgets
    from PyQt5.QtWidgets import QDialog, QPushButton

    from demoGen import Ui_demoGen

    class demo(QtWidgets.QDialog):
    selected_item = ''

    def Save(self):
    self.selected_item = self.ui.demo_cb.currentText()
    self.done(0)
    return(self.selected_item)

    def closeEvent(self, event):
    event.accept()

    def __init__(self, info, drive_list):
    super(demo, self).__init__()
    self.ui = Ui_demoGen()
    self.ui.setupUi(self)

    self.selected_item = '#'
    self.ui.demo_save_btn.clicked.connect(lambda: self.Save())

    if info:
    self.ui.labe_1.setText(info)
    self.ui.demo_cb.clear()
    self.ui.demo_cb.addItems(item_list)
    self.ui.demo_cb.setCurrentIndex(-1)
    self.ui.demo_save_btn.setFocus()

    if info:
    self.ui.labe_1.setText(info)
    self.ui.demo_cb.clear()
    self.ui.demo_cb.addItems(item_list)
    self.ui.demo_cb.setCurrentIndex(-1)
    self.ui.demo_save_btn.setFocus()

    if __name__ == "__main__":

    app = QtWidgets.QApplication([])
    info = 'Select Item'
    item_list = ['A','B','C','D','E']
    application = demo( info, list(reversed(item_list)))
    application.exec_()
    val = application.Save()
    if val == '':
    print('Z')
    else:
    print('val is ',val)

    Continue reading...

Compartilhe esta Página