"Create a program in PyQt that is aimed towards benefiting a local community library. The program should be able to add, edit and delete book entries to and from the inventory list.
Include one list widget, one line edit box, one label, four push buttons."
I can drag and drop all these things into PyQt5, save it as .ui, convert to .py and open in IDLE, but how do I make the buttons do anything? Also, how do I get my IDLE to display this box?
This is what the program should look like
This is the code I am left with after saving the .ui file and converting to .py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'listoper.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 450)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(260, 180, 256, 192))
self.listWidget.setObjectName("listWidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(10, 230, 171, 91))
self.lineEdit.setObjectName("lineEdit")
self.Enterbookdetails = QtWidgets.QLabel(self.centralwidget)
self.Enterbookdetails.setGeometry(QtCore.QRect(20, 200, 101, 16))
self.Enterbookdetails.setObjectName("Enterbookdetails")
self.Add = QtWidgets.QPushButton(self.centralwidget)
self.Add.setGeometry(QtCore.QRect(10, 330, 75, 23))
self.Add.setObjectName("Add")
self.Delete = QtWidgets.QPushButton(self.centralwidget)
self.Delete.setGeometry(QtCore.QRect(110, 330, 75, 23))
self.Delete.setObjectName("Delete")
self.Edit = QtWidgets.QPushButton(self.centralwidget)
self.Edit.setGeometry(QtCore.QRect(10, 370, 75, 23))
self.Edit.setObjectName("Edit")
self.Deleteall = QtWidgets.QPushButton(self.centralwidget)
self.Deleteall.setGeometry(QtCore.QRect(110, 370, 75, 23))
self.Deleteall.setObjectName("Deleteall")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.Enterbookdetails.setText(_translate("MainWindow", "Enter Book Details:"))
self.Add.setText(_translate("MainWindow", "Add"))
self.Delete.setText(_translate("MainWindow", "Delete"))
self.Edit.setText(_translate("MainWindow", "Edit"))
self.Deleteall.setText(_translate("MainWindow", "Delete All"))
Apparently I am supposed to use the following code, but my buttons still don't work:
The kilogram to pound button:
def btn_KtoP_clicked(self):
kilo = float(self.edt_Kilo.text())
pound = (kilo * 2.2)
self.edt_Pounds.setText(str(pound))
The pound to kilogram button:
def btn_PtoK_clicked(self):
pound = float(self.edt_Pounds.text())
kilo = (pound/2.2)
self.edt_Kilo.setText(str(kilo))
Based on your above code, this should work
import sys
from PyQt5 import QtCore, QtWidgets
from YOUR_UI_MODULE import Ui_MainWindow
class sow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.main_ui=Ui_MainWindow()
self.main_ui.setupUi(self)
self.main_ui.Add.clicked.connect(self.doAdd)
self.main_ui.Edit.clicked.connect(self.doEdit)
def doAdd(self):
print("do add")
def doEdit(self):
print("do edit")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = sow()
myapp.show()
sys.exit(app.exec_())
checkout the examples which came with your PyQT5 installation and start from there.
mine is located here C:\Python34\Lib\site-packages\PyQt5\examples
PyQT has a reference doc, mine is located here C:/Python32/Lib/site-packages/PyQt4/doc/html/classes.html
I will recommend reading this tutorial before coding further, so you know what you are doing.
http://zetcode.com/gui/pyqt5/firstprograms/
Related
I'm making a GUI with PyQt5.
I'm very very new to it. I need help.
First i have a stacked widget that I can use to switch between pages.
Right now im trying to make a setings page.
Settings Page
I know that putting stacked widgets for changing like "window"/page in pyqt5 might not be the best but ignore if you want to (if its bad give me a suggestion please).
Right now I want to check if the Dark Mode checkbox is enabled.
I have a MainWindow.py and I have a gui.py which is the one that I transformed from a .ui to .py (pyuic5 cmd).
In MainWindow.py I'm handling all of the gui's "commands/buttons".
gui.py is the file with all of the gui imported from qt designer.
I also have settings.config which is the files where I try to save the settings.
BTW my main idea was to write when the check box was clicked to save the thing to the .config file (which it does) and then check from MainWindow.py if the text == 'Dark Mode: True'
The Big Question How do I make it so the checkbox can be checked from another file (MainWindow.py)?
Also, if not should I change how the gui is handled and stuff.
Heres my code BTW:
The MainWindow.py Script:
import sys
import PyQt5
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from gui import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
class MainWindow:
def __init__(self):
self.main_win = QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.main_win)
self.main_win.setWindowTitle("GUI App")
self.ui.stackedWidget.setCurrentWidget(self.ui.start)
# Start Screen
self.ui.startButton.clicked.connect(self.showHomeScreen)
self.ui.settingsButton.clicked.connect(self.showSettingsScreen)
# Settings Screen
self.ui.backStartButton.clicked.connect(self.showStartScreen)
self.ui.darkModeEnabled.clicked.connect(self.checkDarkMode)
# Home Screen
self.ui.backToStartHome.clicked.connect(self.showStartScreen)
def showHomeScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.home)
# Start Screen Funcions
def showStartScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.start)
# Settings Functions
def showSettingsScreen(self):
self.ui.stackedWidget.setCurrentWidget(self.ui.settings)
def checkDarkMode(self):
if self.ui.darkModeEnabled.isChecked() == True:
self.f = open('settings.config', 'w')
self.f.write("Darkmode: True")
self.f.close()
if self.ui.darkModeEnabled.isChecked() == False:
self.f = open('settings.config', 'w')
self.f.write("Darkmode: False")
self.f.close()
for line in open('settings.config', 'r'):
if line == 'Darkmode: True':
self.ui.darkModeEnabled.setChecked(True)
print('Darkmode is on!')
elif line == 'Darkmode: False':
self.ui.darkModeEnabled.setChecked(False)
print('Darkmode is off!')
def show(self):
self.main_win.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_win = MainWindow()
main_win.show()
sys.exit(app.exec_())
The gui.py script:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(597, 319)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(-21, -11, 651, 321))
self.stackedWidget.setObjectName("stackedWidget")
self.start = QtWidgets.QWidget()
self.start.setObjectName("start")
self.label = QtWidgets.QLabel(self.start)
self.label.setGeometry(QtCore.QRect(130, 30, 351, 81))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.startButton = QtWidgets.QPushButton(self.start)
self.startButton.setGeometry(QtCore.QRect(150, 180, 131, 51))
self.startButton.setObjectName("startButton")
self.settingsButton = QtWidgets.QPushButton(self.start)
self.settingsButton.setGeometry(QtCore.QRect(310, 180, 131, 51))
self.settingsButton.setObjectName("settingsButton")
self.stackedWidget.addWidget(self.start)
self.home = QtWidgets.QWidget()
self.home.setObjectName("home")
self.label_2 = QtWidgets.QLabel(self.home)
self.label_2.setGeometry(QtCore.QRect(160, 30, 351, 81))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.backToStartHome = QtWidgets.QPushButton(self.home)
self.backToStartHome.setGeometry(QtCore.QRect(34, 42, 91, 51))
self.backToStartHome.setObjectName("backToStartHome")
self.stackedWidget.addWidget(self.home)
self.settings = QtWidgets.QWidget()
self.settings.setObjectName("settings")
self.label_3 = QtWidgets.QLabel(self.settings)
self.label_3.setGeometry(QtCore.QRect(130, 0, 431, 111))
font = QtGui.QFont()
font.setFamily("MS Gothic")
font.setPointSize(48)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
self.backStartButton = QtWidgets.QPushButton(self.settings)
self.backStartButton.setGeometry(QtCore.QRect(30, 40, 91, 31))
self.backStartButton.setObjectName("backStartButton")
self.darkModeEnabled = QtWidgets.QCheckBox(self.settings)
self.darkModeEnabled.setGeometry(QtCore.QRect(30, 130, 111, 21))
font = QtGui.QFont()
font.setFamily("MS Reference Sans Serif")
font.setPointSize(12)
self.darkModeEnabled.setFont(font)
self.darkModeEnabled.setObjectName("darkModeEnabled")
self.stackedWidget.addWidget(self.settings)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 597, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Start Page"))
self.startButton.setText(_translate("MainWindow", "Start"))
self.settingsButton.setText(_translate("MainWindow", "Settings"))
self.label_2.setText(_translate("MainWindow", "Home Page"))
self.backToStartHome.setText(_translate("MainWindow", "Back to Start"))
self.label_3.setText(_translate("MainWindow", "Settings Page"))
self.backStartButton.setText(_translate("MainWindow", "Back to Start"))
self.darkModeEnabled.setText(_translate("MainWindow", "Dark Mode"))
If you read all of this and know how to fix this please help.
And if you didn't but just know please help.
Thank You
This question already has answers here:
How to add functions to Qt buttons from .ui file?
(2 answers)
How to link Qt Designer button to a function in a separate file [duplicate]
(1 answer)
QtDesigner changes will be lost after redesign User Interface
(2 answers)
Closed 12 months ago.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(60, 160, 201, 81))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(60, 110, 201, 41))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(70, 50, 191, 41))
self.label.setText("")
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Push ME!!"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Sorry if this is a very basic question, but I've tried to search from Google to Youtube without result. So, please help me.
I want to make so that when I click the button with the text inside lineedit is "OK", the result will show up in label with this sentence: "You're Good!"
Thank you!
Read this bit first:
This is a trivial example - but I'd strongly recommend you completely decouple any logic onto separate .py files from your GUI. That allows changes to with the GUI editor without losing your logic.
Anyway, I've stuck with your architecture such as it is for this answer - but I'd really advise you steer away from it ASAP.
.ui - .py should be their own file(s)
pythonInterfaceToGUI.py should be their own file(s)
pythonLogic.py - should be their own file(s)
pythonInterfaceToGUI defines the hooks to the GUI and the calls to the logic.
You need to connect the button to something, did you come across anything like:
self.pushbutton.clicked.connect(self.foo)
and here foo would be
def foo(self):
self.lineEdit.setText("Your good!")
Put together, here your .py would be:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(60, 160, 201, 81))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(60, 110, 201, 41))
self.lineEdit.setObjectName("lineEdit")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(70, 50, 191, 41))
self.label.setText("")
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.pushButton.clicked.connect(self.foo)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Push ME!!"))
def foo(self):
self.lineEdit.setText("Your good!")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I tried to design a very basic GUI app that shows the entered height on a dialog, but after I press the ‘OK’ button on the main window, the whole program crashes and the process finishes with this exit code:
Process finished with exit code -1073740791 (0xC0000409)
Here’s the full code for the app, the UI files are below:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import *
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
self.mid_label.setText(My_Window.mid_label_nexttext)
class My_Window(QMainWindow):
def __init__(self):
super(My_Window, self).__init__()
loadUi("mainwindow.ui", self)
self.mid_label_nexttext = None
self.height_selecter_spinbox.textChanged.connect(lambda x: self.spin_changed(x))
self.pushButton.clicked.connect(self.onMyPushButtonClick)
def onMyPushButtonClick(self):
dlg = My_Dialog()
if dlg.exec_():
print("Success!")
else:
print("Cancel!")
def spin_changed(self, s):
self.mid_label_nexttext = s
self.update()
def main():
app = QApplication(sys.argv)
window = My_Window()
window.show()
app.exec_()
if __name__ == "__main__":
main()
The main window’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(513, 171)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(310, 80, 75, 23))
self.pushButton.setObjectName("pushButton")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(90, 40, 209, 29))
self.layoutWidget.setObjectName("layoutWidget")
self.layout = QtWidgets.QHBoxLayout(self.layoutWidget)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setObjectName("layout")
self.label_firstpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_firstpart.setFont(font)
self.label_firstpart.setObjectName("label_firstpart")
self.layout.addWidget(self.label_firstpart)
self.height_selecter_spinbox = QtWidgets.QSpinBox(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(13)
self.height_selecter_spinbox.setFont(font)
self.height_selecter_spinbox.setMinimum(100)
self.height_selecter_spinbox.setMaximum(250)
self.height_selecter_spinbox.setProperty("value", 175)
self.height_selecter_spinbox.setObjectName("height_selecter_spinbox")
self.layout.addWidget(self.height_selecter_spinbox)
self.label_lastpart = QtWidgets.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(15)
self.label_lastpart.setFont(font)
self.label_lastpart.setObjectName("label_lastpart")
self.layout.addWidget(self.label_lastpart)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "OK"))
self.label_firstpart.setText(_translate("MainWindow", "My height is "))
self.label_lastpart.setText(_translate("MainWindow", "cm."))
The dialog’s UI:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dialog.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.dialog_buttonbox = QtWidgets.QDialogButtonBox(Dialog)
self.dialog_buttonbox.setGeometry(QtCore.QRect(30, 240, 341, 32))
self.dialog_buttonbox.setOrientation(QtCore.Qt.Horizontal)
self.dialog_buttonbox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.dialog_buttonbox.setObjectName("dialog_buttonbox")
self.widget = QtWidgets.QWidget(Dialog)
self.widget.setGeometry(QtCore.QRect(80, 90, 151, 41))
self.widget.setObjectName("widget")
self.dialog_layout = QtWidgets.QHBoxLayout(self.widget)
self.dialog_layout.setContentsMargins(0, 0, 0, 0)
self.dialog_layout.setObjectName("dialog_layout")
self.left_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.left_label.setFont(font)
self.left_label.setObjectName("left_label")
self.dialog_layout.addWidget(self.left_label)
self.mid_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.mid_label.setFont(font)
self.mid_label.setObjectName("mid_label")
self.dialog_layout.addWidget(self.mid_label)
self.right_label = QtWidgets.QLabel(self.widget)
font = QtGui.QFont()
font.setPointSize(12)
self.right_label.setFont(font)
self.right_label.setObjectName("right_label")
self.dialog_layout.addWidget(self.right_label)
self.retranslateUi(Dialog)
self.dialog_buttonbox.accepted.connect(Dialog.accept)
self.dialog_buttonbox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.left_label.setText(_translate("Dialog", "You are"))
self.mid_label.setText(_translate("Dialog", "100"))
self.right_label.setText(_translate("Dialog", "cm tall."))
I would appreciate some help on fixing this error, and on why it occured.
You are trying to access an attribute that does not exist:
self.mid_label.setText(My_Window.mid_label_nexttext)
My_Window is a class, while mid_label_nexttext was assigned to the instance of that class (self is always the reference to the current instance).
If you want to set the text for that label from a "parent" window, you either add an extra argument to the __init__ that allows to get the text, or you set it from the main window.
Use the text as init argument
class My_Dialog(QDialog):
def __init__(self, text):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# ensure that "text" is a valid string, you can't use setText(None)
if text:
self.mid_label.setText(text)
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog(self.mid_label_nexttext)
# ...
Set the text from the parent
class My_Dialog(QDialog):
def __init__(self):
super(My_Dialog, self).__init__()
loadUi("dialog.ui", self)
# NO setText() here!!!
class My_Window(QMainWindow):
# ...
def onMyPushButtonClick(self):
dlg = My_Dialog()
if self.mid_label_nexttext:
dlg.mid_label.setText(self.mid_label_nexttext)
# ...
Note that the first method is usually better, mostly for modularity reasons: let's say that you create that dialog from different classes in different situations, whenever you need to change the object name of the label (or the whole interface structure) you can easily change its reference in the dialog subclass, otherwise you'll need to change every reference in your code.
Note: the call to self.update() is useless; if you want to update the label on the dialog whenever the spinbox value is changed, you need to directly access the label (like in the last example) or use signals. Also, you don't need to use lambda if you're using the same argument parameter, just connect to the function.
I am learning PyQt5, I am trying to create a message box , but its keep giving me error
Traceback (most recent call last):
File "addition_code_main.py", line 47, in clickMethod
QMessageBox.about(self, "Title", "Message")
TypeError: about(QWidget, str, str): argument 1 has unexpected type 'MainWindow_EXEC'
The code I have is is bellow, I am not understanding what i am doing wrong, where to pass this Qwidget parameter,
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QMessageBox
from addition_code import Ui_MainWindow
class MainWindow_EXEC():
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(MainWindow)
self.connect_singals()
MainWindow.show()
sys.exit(app.exec_())
def connect_singals(self):
self.ui.pushButton_3.clicked.connect(self.clickMethod)
def clickMethod(self):
QMessageBox.about(self, "Title", "Message")
if __name__ == "__main__":
MainWindow_EXEC()
addition_code.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'addition_code.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(150, 40, 113, 20))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(430, 40, 113, 20))
self.lineEdit_2.setObjectName("lineEdit_2")
self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_3.setGeometry(QtCore.QRect(290, 40, 113, 20))
self.lineEdit_3.setObjectName("lineEdit_3")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(260, 100, 81, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(400, 110, 75, 23))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(250, 190, 75, 23))
self.pushButton_3.setObjectName("pushButton_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Addtion"))
self.pushButton_2.setText(_translate("MainWindow", "MysqlConnect"))
self.pushButton_3.setText(_translate("MainWindow", "MessagesBox"))
To understand the problem, just check the documentation:
void QMessageBox::about(QWidget *parent, const QString &title, const QString &text)
Displays a simple about box with title title and text text. The about
box's parent is parent.
about() looks for a suitable icon in four locations:
It prefers parent->icon() if that exists.
If not, it tries the top-level widget containing parent.
If that fails, it tries the active window.
As a last resort it uses the Information icon.
The about box
has a single button labelled "OK". On macOS, the about box is popped
up as a modeless window; on other platforms, it is currently
application modal.
As you can see the first parameter must be a QWidget or None but you are passing it a MainWindow_EXEC instance that does not meet that condition by throwing that error.
Considering the above there are several possible solutions:
Pass None as the first parameter.
def clickMethod(self):
QMessageBox.about(None, "Title", "Message")
Move to MainWindow so you have to become a class member.
class MainWindow_EXEC:
def __init__(self):
app = QtWidgets.QApplication(sys.argv)
self.MainWindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
self.connect_singals()
self.MainWindow.show()
sys.exit(app.exec_())
def connect_singals(self):
self.ui.pushButton_3.clicked.connect(self.clickMethod)
def clickMethod(self):
QMessageBox.about(self.MainWindow, "Title", "Message")
I'm trying to create a GUI program using PyQT5. I'm new to programming and Python so if I'm explaining things in the wrong way please correct me.
I have a main window that will contain multiple QLineEdit widgets and corresponding "Clear" buttons to clear the user entered data. The main window also contains "Edit" buttons to dispay specific dialog boxes where the data can also be edited. My example has a "User ID" QLineEdit widget/text box, "Clear" and "Edit" push buttons.
The dialog box that appears when "Edit' is clicked has it's own "Clear" button. If the Clear button in the dialog window is clicked, both the QLineEdit widget in the dialog and main window should be cleared.
Problem: When I inherit the main window class from the dialog class the method, clearUserID(), used to clear the User ID field fails to be invoked.
When I do not inherit from the main window class the clearUserID method works and I am able to clear the dialog QLineEdit (UserIDWin_UserID_lnedt) but not the corresponding widget on the main window (UserID_lnedt). All of the code I've tried to clear the main window QLineEdit widget using the dialog "Clear" button caused my program to crash.
Would somebody please help me to better understand the logic behind these principles and how to get my code working? Thank you.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(820, 611)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
self.tabWidget.setObjectName("tabWidget")
self.MainTab = QtWidgets.QWidget()
self.MainTab.setObjectName("MainTab")
self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
self.label = QtWidgets.QLabel(self.MainTab)
self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
self.UserID_le.setObjectName("UserID_le")
self.tabWidget.addTab(self.MainTab, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
self.label.setText(_translate("MainWindow", "User ID"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))
def openUserIDWin(self):
UserID_value = self.UserID_le.text()
UserIDWin = QtWidgets.QDialog()
ui = Ui_UserIDWin(UserID_value)
ui.setupUi(UserIDWin)
UserIDWin.exec_();
class Ui_UserIDWin(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, userID):
print("The User ID is:" + userID)
self.userID = userID
def setupUi(self, UserIDWin):
UserIDWin.setObjectName("UserIDWin")
UserIDWin.resize(400, 124)
self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
self.UserIDWin_UserID_lnedt.setText(self.userID)
self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")
self.retranslateUi(UserIDWin)
QtCore.QMetaObject.connectSlotsByName(UserIDWin)
#If I do not inherit from "QtWidgets.QMainWindow, Ui_MainWindow" the code below works and invokes clearUserId(). However, I then am having problems using SetText on the main window UserId_le text box and the program crashes.
self.UserIDWin_UserIDClear_pushb.clicked.connect(self.clearUserID)
def retranslateUi(self, UserIDWin):
_translate = QtCore.QCoreApplication.translate
UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))
def clearUserID(self):
self.UserIDWin_UserID_lnedt.setText('')
# The line below crashes my program if I am able to invoke this method.
#self.Ui_MainWindow.UserID_le.setText('')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
It seems that they have certain clear concepts about inheritance and good practices but others do not like the following:
PyQt recommends not modifying the code generated by Qt Designer because you probably want to modify the GUI in the future and when using pyuic the initial code is overwritten. Another problem is that beginners do not understand that the class generated by Qt Designer is not a widget but an interface that serves to fill another widget, and consequently can not overwrite the methods of the widgets in addition to other problems.
You only have to modify the object of a class from the object of another class if both have the same scope, in your case when wanting to clean the QLineEdit of the main window from the other window is a dangerous task, instead you should do that logic where both windows have the same scope and that is in the openUserIDWin method.
QLineEdit already has the clear() method that allows to clean, it fulfills the same function as setText("") but the first method is more readable.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(820, 611)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(0, 0, 801, 551))
self.tabWidget.setObjectName("tabWidget")
self.MainTab = QtWidgets.QWidget()
self.MainTab.setObjectName("MainTab")
self.UserID_Edit_pb = QtWidgets.QPushButton(self.MainTab)
self.UserID_Edit_pb.setGeometry(QtCore.QRect(210, 10, 31, 23))
self.UserID_Edit_pb.setObjectName("UserID_Edit_pb")
self.UserID_Clear_pb_2 = QtWidgets.QPushButton(self.MainTab)
self.UserID_Clear_pb_2.setGeometry(QtCore.QRect(170, 9, 41, 23))
self.UserID_Clear_pb_2.setObjectName("UserID_Clear_pb_2")
self.UserID_le = QtWidgets.QLineEdit(self.MainTab)
self.label = QtWidgets.QLabel(self.MainTab)
self.label.setGeometry(QtCore.QRect(10, 10, 47, 13))
self.UserID_le.setGeometry(QtCore.QRect(50, 10, 113, 20))
self.UserID_le.setObjectName("UserID_le")
self.tabWidget.addTab(self.MainTab, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 820, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.UserID_Edit_pb.setText(_translate("MainWindow", "Edit"))
self.UserID_Clear_pb_2.setText(_translate("MainWindow", "Clear"))
self.label.setText(_translate("MainWindow", "User ID"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.MainTab), _translate("MainWindow", "Tab"))
class Ui_UserIDWin(object):
def setupUi(self, UserIDWin):
UserIDWin.setObjectName("UserIDWin")
UserIDWin.resize(400, 124)
self.UserIDWin_UserID_lnedt = QtWidgets.QLineEdit(UserIDWin)
self.UserIDWin_UserID_lnedt.setGeometry(QtCore.QRect(20, 50, 113, 20))
self.UserIDWin_UserID_lnedt.setObjectName("UserIDWin_UserID_lnedt")
self.UserIDWin_UserID_lbl = QtWidgets.QLabel(UserIDWin)
self.UserIDWin_UserID_lbl.setGeometry(QtCore.QRect(20, 30, 47, 13))
self.UserIDWin_UserID_lbl.setObjectName("UserIDWin_UserID_lbl")
self.UserIDWin_UserIDClear_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_UserIDClear_pushb.setGeometry(QtCore.QRect(140, 50, 41, 23))
self.UserIDWin_UserIDClear_pushb.setObjectName("UserIDWin_UserIDClear_pushb")
self.UserIDWin_Cancel_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Cancel_pushb.setGeometry(QtCore.QRect(110, 80, 75, 23))
self.UserIDWin_Cancel_pushb.setObjectName("UserIDWin_Cancel_pushb")
self.UserIDWin_Next_pushb = QtWidgets.QPushButton(UserIDWin)
self.UserIDWin_Next_pushb.setGeometry(QtCore.QRect(190, 80, 75, 23))
self.UserIDWin_Next_pushb.setObjectName("UserIDWin_Next_pushb")
self.retranslateUi(UserIDWin)
QtCore.QMetaObject.connectSlotsByName(UserIDWin)
def retranslateUi(self, UserIDWin):
_translate = QtCore.QCoreApplication.translate
UserIDWin.setWindowTitle(_translate("UserIDWin", "Dialog"))
self.UserIDWin_UserID_lbl.setText(_translate("UserIDWin", "User ID"))
self.UserIDWin_UserIDClear_pushb.setText(_translate("UserIDWin", "Clear"))
self.UserIDWin_Cancel_pushb.setText(_translate("UserIDWin", "Cancel"))
self.UserIDWin_Next_pushb.setText(_translate("UserIDWin", "Next"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.UserID_Edit_pb.clicked.connect(self.openUserIDWin)
self.UserID_Clear_pb_2.clicked.connect(self.UserID_le.clear)
def openUserIDWin(self):
UserID_value = self.UserID_le.text()
w = UserIDWin(UserID_value)
w.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserID_le.clear)
w.exec_()
class UserIDWin(QtWidgets.QDialog, Ui_UserIDWin):
def __init__(self, userID, parent=None):
super(UserIDWin, self).__init__(parent)
self.setupUi(self)
self.userID = userID
self.UserIDWin_UserID_lnedt.setText(self.userID)
self.UserIDWin_UserIDClear_pushb.clicked.connect(self.UserIDWin_UserID_lnedt.clear)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I recommend you read:
http://pyqt.sourceforge.net/Docs/PyQt5/designer.html
QtDesigner changes will be lost after redesign User Interface