I am working on pyqt5 project where I have login window and registration window. I have a button on login window which when clicked should open the registration window. I have designed the ui in qt desginer and have converted the .ui files to .py files using pyuic.
So I have two files login_ui.py and register_window_ui.py. To use them, I have also created two separate files i.e. login.py and register.py which contains all the functional code of the ui files.
Below is the files code:
login.py
import sys
import os
from PyQt5 import QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from ui.login_ui import Ui_login_main_window
from ui.register_window_ui import Ui_register_window
curr_path = os.path.dirname(os.path.abspath(__file__))
class Login(QMainWindow, Ui_login_main_window):
def __init__(self):
QMainWindow.__init__(self)
self.login_ui = Ui_login_main_window()
self.login_ui.setupUi(self)
self.login_ui.register_settings_btn.clicked.connect(self.show_registration_window)
def show_registration_window(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_register_window()
self.ui.setupUi(self.window)
self.window.show()
app = QApplication(sys.argv)
main_window = Login()
main_window.show()
sys.exit(app.exec_())
register.py
import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow
from ui.register_window_ui import Ui_register_window
curr_path = os.path.dirname(os.path.abspath(__file__))
class Register(QMainWindow, Ui_register_window):
def __init__(self):
QMainWindow.__init__(self)
self.register_win_ui = Ui_register_window()
self.register_win_ui.setupUi(self)
self.register_win_ui.register_trial_btn.clicked.connect(self.print_data)
def print_data(self):
print("Clicked")
app = QApplication(sys.argv)
main_window = Register()
main_window.show()
sys.exit(app.exec_())
As you can see that in login.py I have created a button click event for register_settings_btn which when clicked will show Ui_register_window() which is register_window. So when I click it, it shows me the window but the window is not functional i.e. there is no button click event happening. For ex in register.py I have created a button click event which is not working.
Can anyone please explain me why is it not working. Please help. Thanks
I have a button on login window which when clicked should open the registration window
instead of creating 2 QApplications create only 1 and show or exec 1st the login, validate the input and if everything is ok, then show the Register
i.e. instead do something like:
app = QApplication(sys.argv)
login_window = Login()
result = login_window.exec()
if result == ???:
register_window = Register()
register_window.show()
else:
showMsg('Login failed!')
sys.exit(app.exec_())
update! create another file i.e. myProject.py and add this!
#!/usr/local/bin/python
# coding: utf-8
import os, sys
add your imports here!
if __name__ == "__main__":
app = QApplication(sys.argv)
#create login view nd register view
login_window = Login()
register_window = Register()
#execute the view login and read the doc, this will block the code until the user quit the view!
result = login_window.exec()
#define a condition to proof the validity of login process
if result == ???:
#show the register
register_window.show()
else:
#or show the error msg
showMsg('Login failed!')
sys.exit(app.exec_())
Related
So i am making a GUI to identify seagulls.
I have made some QMainWindow's and would like the user to nagviate through these using buttons.
The first window works fine, and the user gets to the next page.
However, when clicking on buttons on page 2, nothing works, not even printing a simple statement. I am new to this and i am doing something wrong. I tried messing with init but am at a loss.
I am using a function
def openNewPage(self,b):
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
to open a new page by having the buttons clicked on by the user have the name of the next file to be opened.
For example: the button for white head has the text "WhiteHead"
and will the open the file WhiteHead.ui
example:
self.bWhiteHead.clicked.connect(lambda:self.openNewPage(self.bWhiteHead))
Please help me understand why buttons work in one window and not in the next, thank you.
Here is the code:
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import Qt
from PyQt6 import uic
import time
class MyApp(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("SeagullPage1.ui",self)
self.setWindowTitle("SEAGULL IDENTIFIER")
self.bBlackHead.clicked.connect(lambda:self.openNewPage(self.bBlackHead))
self.bWhiteHead.clicked.connect(lambda:self.openNewPage(self.bWhiteHead))
def openNewPage(self,b):
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
class WhiteHead(QMainWindow):
def __init__(self):
super().__init__
self.setWindowTitle("SEAGULL IDENTIFIER2")
self.BlackFeetButton.clicked.connect(lambda:self.openNewPage(self.BlackFeetButton))
self.PinkFeetButton.clicked.connect(lambda:self.openNewPage(self.PinkFeetButton))
self.YellowFeetButton.clicked.connect(lambda:self.openNewPage(self.YellowFeetButton))
def openNewPage(self,b):
print("hey")
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
class YellowFeet(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("SEAGULL IDENTIFIER3")
self.RedBeakButton.clicked.connect(lambda:self.openNewPage(self.RedBeakButton))
self.NonReadBeakButton.clicked.connect(lambda:self.openNewPage(self.NonReadBeakButton))
def openNewPage(self,b):
print("hey")
NewPage = b.text()
uic.loadUi(f"{NewPage}.ui",self)
self.show
if __name__ == "__main__":
app = QApplication(sys.argv)
myApp = MyApp()
myApp.show()
app.exec()
#sys.exit(app.exec_())
I'm trying to restart my application after an update from the client side. I was able to achieve till the auto update part. I tried to surf on How to restart PyQt application?. There are few similar questions earlier, but none of them have good explanation or example with a button click event. Could you guys help me understand on how to reboot a PyQt application. Basically I want to restart the application from if __name__ == '__main__': everytime there is an update.
Note: AppLogin is my private module I created to handle application login. So basically that would be the landing QDialog once application is opened.
from PyQt5.QtWidgets import *
import sys
import AppLogin
class App:
def __init__(self):
btn = QPushButton(main_window)
btn.setText('close')
btn.pressed.connect(self.restart)
main_window.show()
def restart(self):
# Here goes the code for restart
pass
if __name__ == '__main__':
appctxt = QApplication(sys.argv)
log_in = AppLogin.Login()
if log_in.exec_() == QDialog.Accepted:
main_window = QMainWindow()
ui = App()
exit_code = appctxt.exec_()
sys.exit(exit_code)
The logic is to end the eventloop and launch the application an instant before it closes:
import sys
from PyQt5 import QtCore, QtWidgets
def restart():
QtCore.QCoreApplication.quit()
status = QtCore.QProcess.startDetached(sys.executable, sys.argv)
print(status)
def main():
app = QtWidgets.QApplication(sys.argv)
print("[PID]:", QtCore.QCoreApplication.applicationPid())
window = QtWidgets.QMainWindow()
window.show()
button = QtWidgets.QPushButton("Restart")
button.clicked.connect(restart)
window.setCentralWidget(button)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
A solution is to close (or forget) the QMainWindow and recreate it.
If you just "show()" a single widget, the same idea works fine.
import sys
import uuid
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
singleton: 'MainWindow' = None
def __init__(self):
super().__init__()
btn = QPushButton(f'RESTART\n{uuid.uuid4()}')
btn.clicked.connect(MainWindow.restart)
self.setCentralWidget(btn)
self.show()
#staticmethod
def restart():
MainWindow.singleton = MainWindow()
def main():
app = QApplication([])
MainWindow.restart()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
actually I try to do a displayer of html page. I have some of list of html that I need to display, each page must stay visible while x secondes.
But, after the first page is display, the application crash and the python shell restart in consequence.
On my mind, I would create the window to display the page and close the application because after I will try to display png/jpg, so I need to close app to use Pygame for pictures and re-build the app to display html page after.
My list looking for it :
html page/html page/picture/html page/picture/picture
So I have build a sample code to test in while boucle the displayer :
from PyQt5 import QtWidgets, QtWebEngineWidgets, QtCore
import sys
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle('My first rendering')
# Add layout
layout = QtWidgets.QVBoxLayout()
win.setLayout(layout)
# Create QWebView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl('https://google.com'))
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7*1000, win.close)
QtCore.QTimer.singleShot(7*1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print('Close Application')
print("End While Loop")
Result after executing
It's probably sys.argv in app var the mistake, but I'm new in Python so I don't know how to fix the problem.
The problem is that QApplication is not necessarily eliminated and therefore you would be creating more than one QApplication what Qt forbids, a better solution is to rethink it verifying that if it does not exist then create a new one:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle("My first rendering")
# Create QWebEngineView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl("https://google.com"))
# Add layout
layout = QtWidgets.QVBoxLayout(win)
win.setLayout(layout)
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7 * 1000, win.close)
QtCore.QTimer.singleShot(7 * 1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print("Close Application")
print("End While Loop")
I am new to Python and to PyQt. I have designed GUIs in MATLAB so its been a frustrating new experience. Right now, I have a main window and I want to open another login window on button push. What I have not decided is whether it should return the value of login to the parent window or another window. But either way I need to be able to open the login window through the pushbutton. I have created 2 files declaring the GUI one as a mainwindow and another as Dialog (does not seem like it is inheriting from QDialog though). The other 2 py files are classed calling the UIs separately and work fine. Each have their functions. I am pasting the main.py (mainwindow init and onOpen function code) along with logindialog.py init function code. Kindly help or else I will have to go back to Matlab where I can do this quite easily.`
import sys
from PyQt5 import QtWidgets, QtGui
from LoginDialog import LoginDialog
import UI_MSLDB_Main
from UI_LoginDialog import Ui_LoginDialog
#import Helper
#import Auth
#import TestFeature01
class Main(QtWidgets.QMainWindow, UI_MSLDB_Main.Ui_MSLDatabase):
def _init_(self, parent = None):
QtWidgets.QMainWindow._init_(self)
self.setupUi(self)
self.child = LoginDialog(self)
self.child.setupUi(QtWidgets.QDialog())
# self.createConnections()
self.pushButton_OpenPrimarylist.clicked.connect(self.onOpen)
def onOpen(self):
# window = QtWidgets.QDialog
# self.child = LoginDialog(window, Ui_LoginDialog)
# self.child.show()
# exec('LoginDialog.py')
self.child.show
# self.actionStudy.triggered.connect()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
# LoginDialog(QDialog, Ui_LoginDialog)
# loginDialog = LoginDialog(QDialog, UI_LoginDialog)
# username = loginDialog.username
# password =loginDialog.password
# Helper.dbConnect(username,password)
# isAuth = False
# result = -1
# while not isAuth:
# result = loginDialog.exec()
# if result == LoginDialog.Success or result == LoginDialog.Rejected:
# isAuth = True
# else:
# isAuth = False
result = 1
if result == 1:#LoginDialog.Success:
MSLDatabase = QtWidgets.QMainWindow()
ui = UI_MSLDB_Main.Ui_MSLDatabase()
ui.setupUi(MSLDatabase)
MSLDatabase.show()
# w.show()
app.exec_()
sys.exit(app.exec_())
There were multiple things I tried not knowing which would work. The commented codes are the ones I have tried and failed. LoginDialog class is below.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QMessageBox
import Auth
import Helper
from UI_LoginDialog import Ui_LoginDialog
class LoginDialog(QDialog, Ui_LoginDialog):
Success, Failed, Rejected, username, password = range(0,5)
def _init_(self):
QDialog._init_(self)
self.setupUi(self)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL
(_fromUtf8("accepted()")),self.onAccept)
QtCore.QObject.connect(self.buttonBox,
QtCore.SIGNAL(_fromUtf8("rejected()")),
self.onReject)
I would like to ask, as I write in the title, how to open a new window and close (completely) the current window?
There are two .py files. They are independent from each other, that means, each of them can be run on its own.
In MyApp.py there is a button. If the button is clicked, I want to close the current window/file and open the new window/file.
In my code below I can open the new window/file, but the old window is not closed. And if I close the second window, the old window will be closed as well. I have tried some methods with my knowledge/search, but none of them worked fine.
Here is the code for MyApp.py
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import NewApp
# NewApp.py in the same folder
# in NewApp.py there is a class NewApp
qtCreatorFile_MyApp = "F:\\MyApp.ui"
class MyApp(QWidget):
def __init__(self):
super(MyApp, self).__init__()
uic.loadUi(qtCreatorFile_MyApp, self)
self.show()
self.btn_inMyApp.clicked.connect(self.closeMyApp_OpenNewApp)
def closeMyApp_OpenNewApp(self):
self.Open = NewApp.NewApp()
self.Open.show()
# My Problem: How to close the MyApp completely and open NewApp?
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MyApp()
sys.exit(app.exec_())
NewApp.py has similar code structure. For the purpose of integrity of this quesiton, I paste the code as follows.
qtCreatorFile_NewApp = "F:\\NewApp.ui"
class NewApp(QWidget):
def __init__(self):
super(NewApp, self).__init__()
uic.loadUi(qtCreatorFile_NewApp, self)
self.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = NewApp()
sys.exit(app.exec_())
Thank you for the help!