I dynamically create a combobox, but later on I can't figure out how to access it to get the current text.
Process finished with exit code -1073740791 (0xC0000409)
from form import Ui_Dialog
from PyQt5 import QtCore, QtWidgets
class MainWindow(Ui_Dialog):
def __init__(self):
super(MainWindow).__init__()
def setupUi(self, Dialog):
super(MainWindow, self).setupUi(Dialog)
self.btn_print.clicked.connect(lambda: print_doc())
class Ui_Dialog_combobox(object):
def __init__(self):
super(MainWindow).__init__()
self.comboBox = QtWidgets.QComboBox(Dialog)
self.comboBox.setGeometry(QtCore.QRect(458, 10, 151, 22))
self.comboBox.setObjectName("comboBox_doctor")
self.comboBox.addItem("")
self.retranslateUi(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.comboBox.setItemText(0, _translate("Dialog", "NAME"))
def print_doc():
name = ui.comboBox.currentText()
print(name)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
Ui_Dialog_combobox()
ui = MainWindow()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
You seem a bit confused on how UI files should be used and how classes and instances work.
First of all, you should not subclass the "form class" alone, you must subclass from the base Qt widget class (QDialog, in this case) and the form class.
Then, the comboBox
you're trying to access is probably the one you created in the Ui_Dialog_combobox
, but you're just creating an instance of that class without assigning it to anything (so, it's completely useless).
Also, lots of the code in that class is problematic: the super()
is incomplete (and wrong, as it refers to another class), and it also makes references to Dialog
which not only is not part of that class, but is also a variable that just "happens" to be in its scope.
So, first of all, NEVER try to mimic the behavior of files generated by pyuic. Actually, you should almost always ignore their contents: you just import and use them. If you look at the official guidelines about using Designer, you'll see that there's no attempt to modify or imitate those files in any way.
Here is a (possible) proper version of your code.
from form import Ui_Dialog
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QDialog, Ui_Dialog):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
self.comboBox = QtWidgets.QComboBox(self)
self.comboBox.setGeometry(QtCore.QRect(458, 10, 151, 22))
self.comboBox.addItem("NAME")
self.btn_print.clicked.connect(self.print_doc)
def print_doc(self):
name = self.comboBox.currentText()
print(name)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
Some further suggestions:
User contributions licensed under CC BY-SA 3.0