name_dialog = QDialog() name_form = QFormLayout() name_input = QLineEdit() name_form.addRow("Name:", name_input) name_dialog.setLayout(name_form) # connect the accept button to the accept method ok_button = QPushButton("OK") ok_button.clicked.connect(name_dialog.accept) name_form.addRow(ok_button) result = name_dialog.exec_() if result == QDialog.Accepted: name = name_input.text() print(f"Hello {name}!")
color_dialog = QDialog() color_form = QFormLayout() color_combo = QComboBox() color_combo.addItems(["Red", "Green", "Blue"]) color_form.addRow("Color:", color_combo) color_dialog.setLayout(color_form) # connect the save button to the accept method save_button = QPushButton("Save") save_button.clicked.connect(color_dialog.accept) color_form.addRow(save_button) result = color_dialog.exec_() if result == QDialog.Accepted: color = color_combo.currentText() print(f"Selected color: {color}")In this example, we create a QDialog box with a QFormLayout that contains a QComboBox for the user to select a color. We then create a QPushButton labeled "Save" and connect its clicked signal to the accept method of the dialog box. When the Save button is clicked, the dialog box is closed and the result code is set to Accepted. We check the result code and if it is Accepted, we retrieve the currently selected text from the QComboBox and print the selected color. Package library: PyQt5.QtWidgets