This question already has answers here:
Calling a function upon button press
(3 answers)
Closed 3 years ago.
fairly new to PyQt and Python in general. I am having trouble applying a click event to a button in PyQt5. I am trying to add functionality to all the buttons I have, although it seems I am missing some initial setup to allow it to work. Looking through the documentation...
pushButton.clicked.connect("Do some action")
..should enable the click functionality on the targeted button.
I do not currently have the connect option available after the pushbutton.connect call.
I assume I am missing some setup in the class.
from PyQt5 import QtCore, QtGui, QtWidgets
import cheekycheeky
import datetime
import ntplib
import time
class ContLCDClock(QtWidgets.QWidget,):
def __init__(self, parent = None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updateLCD1)
self.timer.start(1000)
# self.timer2 = QtCore.QTimer()
# self.timer2.timeout.connect(self.updateLCD2)
# self.timer2.start(4000)
# self.time_format = "%H:%M:%S"
# self.client = ntplib.NTPClient()
# self.response = self.client.request('pool.ntp.org')
# self.clock = time.strftime(self.time_format, time.localtime(self.response.tx_time))
def updateLCD1(self):
self.currentTime = QtCore.QTime.currentTime()
self.strCurrentTime = self.currentTime.toString('hh:mm:ss')
self.ui.lcdNumber.display(self.strCurrentTime)
# def updateLCD2(self):
# self.time_format = "%H:%M:%S"
# self.client = ntplib.NTPClient()
# self.response = self.client.request('pool.ntp.org')
# self.clock = time.strftime(self.time_format, time.localtime(self.response.tx_time))
# self.ui.lcdNumber_2.display(self.clock)
class Ui_Form(object) :
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(335, 157)
self.pushButton_7 = QtWidgets.QPushButton(Form)
self.pushButton_7.setGeometry(QtCore.QRect(50, 120, 31, 23))
self.pushButton_7.setObjectName("pushButton_7")
self.pushButton_7.clicked.connect(print('I am working')) # This does not work
self.pushButton_9 = QtWidgets.QPushButton(Form)
self.pushButton_9.setGeometry(QtCore.QRect(90, 120, 31, 23))
self.pushButton_9.setObjectName("pushButton_9")
self.pushButton_6 = QtWidgets.QPushButton(Form)
self.pushButton_6.setGeometry(QtCore.QRect(210, 120, 31, 23))
self.pushButton_6.setObjectName("pushButton_6")
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(290, 120, 31, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(9, 16, 80, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.pushButton_8 = QtWidgets.QPushButton(Form)
self.pushButton_8.setGeometry(QtCore.QRect(9, 120, 31, 23))
self.pushButton_8.setObjectName("pushButton_8")
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(130, 120, 71, 23))
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_5 = QtWidgets.QPushButton(Form)
self.pushButton_5.setGeometry(QtCore.QRect(250, 120, 31, 23))
self.pushButton_5.setObjectName("pushButton_5")
self.lcdNumber_2 = QtWidgets.QLCDNumber(Form)
self.lcdNumber_2.setGeometry(QtCore.QRect(145, 9, 171, 31))
self.lcdNumber_2.setObjectName("lcdNumber_2")
self.lcdNumber_2.setDigitCount(11)
self.lcdNumber = QtWidgets.QLCDNumber(Form)
self.lcdNumber.setGeometry(QtCore.QRect(145, 59, 171, 31))
self.lcdNumber.setObjectName("lcdNumber")
self.lcdNumber.setDigitCount(8)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(9, 67, 105, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Cheeky Timer"))
self.pushButton_7.setText(_translate("Form", "-.5"))
self.pushButton_9.setText(_translate("Form", "-.1"))
self.pushButton_6.setText(_translate("Form", "+.1"))
self.pushButton_3.setText(_translate("Form", "+1"))
self.label.setText(_translate("Form", "NTP Time:"))
self.pushButton_8.setText(_translate("Form", "-1"))
self.pushButton_4.setText(_translate("Form", "Reset Time"))
self.pushButton_5.setText(_translate("Form", "+.5"))
self.label_2.setText(_translate("Form", "Current Time:"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
c = ContLCDClock()
c.show()
sys.exit(app.exec_())
Thank you in advance for any help, I hope I have been clear enough.
I think it may be because your input is incorrect, an example piece:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)
self.show()
#pyqtSlot()
def on_click(self):
print('PyQt5 button click')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Here a function self.on_click is passed. In your example, you pass print('I am working'), which returns a None. You could fix this for instance like this:
from PyQt5 import QtCore, QtGui, QtWidgets
import cheekycheeky
import datetime
import ntplib
import time
class ContLCDClock(QtWidgets.QWidget,):
def __init__(self, parent = None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.updateLCD1)
self.timer.start(1000)
# self.timer2 = QtCore.QTimer()
# self.timer2.timeout.connect(self.updateLCD2)
# self.timer2.start(4000)
# self.time_format = "%H:%M:%S"
# self.client = ntplib.NTPClient()
# self.response = self.client.request('pool.ntp.org')
# self.clock = time.strftime(self.time_format, time.localtime(self.response.tx_time))
def updateLCD1(self):
self.currentTime = QtCore.QTime.currentTime()
self.strCurrentTime = self.currentTime.toString('hh:mm:ss')
self.ui.lcdNumber.display(self.strCurrentTime)
# def updateLCD2(self):
# self.time_format = "%H:%M:%S"
# self.client = ntplib.NTPClient()
# self.response = self.client.request('pool.ntp.org')
# self.clock = time.strftime(self.time_format, time.localtime(self.response.tx_time))
# self.ui.lcdNumber_2.display(self.clock)
class Ui_Form(object) :
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(335, 157)
self.pushButton_7 = QtWidgets.QPushButton(Form)
self.pushButton_7.setGeometry(QtCore.QRect(50, 120, 31, 23))
self.pushButton_7.setObjectName("pushButton_7")
self.pushButton_7.clicked.connect(self.i_am_working)
self.pushButton_9 = QtWidgets.QPushButton(Form)
self.pushButton_9.setGeometry(QtCore.QRect(90, 120, 31, 23))
self.pushButton_9.setObjectName("pushButton_9")
self.pushButton_6 = QtWidgets.QPushButton(Form)
self.pushButton_6.setGeometry(QtCore.QRect(210, 120, 31, 23))
self.pushButton_6.setObjectName("pushButton_6")
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(290, 120, 31, 23))
self.pushButton_3.setObjectName("pushButton_3")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(9, 16, 80, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.pushButton_8 = QtWidgets.QPushButton(Form)
self.pushButton_8.setGeometry(QtCore.QRect(9, 120, 31, 23))
self.pushButton_8.setObjectName("pushButton_8")
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(130, 120, 71, 23))
self.pushButton_4.setObjectName("pushButton_4")
self.pushButton_5 = QtWidgets.QPushButton(Form)
self.pushButton_5.setGeometry(QtCore.QRect(250, 120, 31, 23))
self.pushButton_5.setObjectName("pushButton_5")
self.lcdNumber_2 = QtWidgets.QLCDNumber(Form)
self.lcdNumber_2.setGeometry(QtCore.QRect(145, 9, 171, 31))
self.lcdNumber_2.setObjectName("lcdNumber_2")
self.lcdNumber_2.setDigitCount(11)
self.lcdNumber = QtWidgets.QLCDNumber(Form)
self.lcdNumber.setGeometry(QtCore.QRect(145, 59, 171, 31))
self.lcdNumber.setObjectName("lcdNumber")
self.lcdNumber.setDigitCount(8)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(9, 67, 105, 19))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Cheeky Timer"))
self.pushButton_7.setText(_translate("Form", "-.5"))
self.pushButton_9.setText(_translate("Form", "-.1"))
self.pushButton_6.setText(_translate("Form", "+.1"))
self.pushButton_3.setText(_translate("Form", "+1"))
self.label.setText(_translate("Form", "NTP Time:"))
self.pushButton_8.setText(_translate("Form", "-1"))
self.pushButton_4.setText(_translate("Form", "Reset Time"))
self.pushButton_5.setText(_translate("Form", "+.5"))
self.label_2.setText(_translate("Form", "Current Time:"))
def i_am_working(self):
print('I am working')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
c = ContLCDClock()
c.show()
sys.exit(app.exec_())
Related
This question already has answers here:
QtDesigner changes will be lost after redesign User Interface
(2 answers)
How to close a QDialog
(4 answers)
Closed 1 year ago.
I've created a program that allows you to login and sign up. When you have the right credentials it opens a window but it doesn't close. The same thing happens when you press the button to sign up. I've tried to use the close method but it doesn't work i always get:
AttributeError: type object 'Ui_Dialog' has no attribute 'close'
here is the full code of all the windows:
Login Page
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QMessageBox
import sqlite3
from welcome import Ui_MainWindow
from signup_page import Ui_Dialog2
import sys
#widget.setCurrentIndex(widget.currentIndex)
class Ui_Dialog(object):
def showMessageBox(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText("WRONG USERNAME/PASSWORD")
def loginCheck(self):
username = self.username_input.text()
password = self.password_input.text()
connection = sqlite3.connect("login.db")
result = connection.execute("SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?", (username, password))
if (len(result.fetchall())) > 0:
self.welcomewindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.welcomewindow)
self.welcomewindow.show()
else:
self.showMessageBox()
def singup(self):
self.signup_page = QtWidgets.QDialog()
self.ui = Ui_Dialog2()
self.ui.setupUi(self.signup_page)
self.signup_page.show()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(591, 457)
self.user_name_label = QtWidgets.QLabel(Dialog)
self.user_name_label.setGeometry(QtCore.QRect(190, 150, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.user_name_label.sizePolicy().hasHeightForWidth())
self.user_name_label.setSizePolicy(sizePolicy)
self.user_name_label.setSizeIncrement(QtCore.QSize(0, 0))
self.user_name_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.user_name_label.setFont(font)
self.user_name_label.setObjectName("user_name_label")
self.password_label = QtWidgets.QLabel(Dialog)
self.password_label.setGeometry(QtCore.QRect(190, 210, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.password_label.sizePolicy().hasHeightForWidth())
self.password_label.setSizePolicy(sizePolicy)
self.password_label.setSizeIncrement(QtCore.QSize(0, 0))
self.password_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.password_label.setFont(font)
self.password_label.setObjectName("password_label")
self.username_input = QtWidgets.QLineEdit(Dialog)
self.username_input.setGeometry(QtCore.QRect(280, 150, 141, 20))
self.username_input.setObjectName("username_input")
self.password_input = QtWidgets.QLineEdit(Dialog)
self.password_input.setGeometry(QtCore.QRect(280, 210, 141, 20))
self.password_input.setObjectName("password_input")
self.password_input.setEchoMode(self.password_input.Password)
self.login_btn = QtWidgets.QPushButton(Dialog)
self.login_btn.setGeometry(QtCore.QRect(200, 260, 81, 31))
font = QtGui.QFont()
font.setPointSize(13)
self.login_btn.setFont(font)
self.login_btn.setObjectName("login_btn")
#########Button Event##########
self.login_btn.clicked.connect(self.loginCheck)
###############################
self.signup_btn = QtWidgets.QPushButton(Dialog)
self.signup_btn.setGeometry(QtCore.QRect(300, 260, 81, 31))
########Button Event##########
self.signup_btn.clicked.connect(self.singup)
##############################
font = QtGui.QFont()
font.setPointSize(13)
self.signup_btn.setFont(font)
self.signup_btn.setObjectName("signup_btn")
self.login_title = QtWidgets.QLabel(Dialog)
self.login_title.setGeometry(QtCore.QRect(240, 40, 91, 71))
font = QtGui.QFont()
font.setPointSize(20)
self.login_title.setFont(font)
self.login_title.setObjectName("login_title")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(130, 370, 391, 31))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Login Page"))
self.user_name_label.setText(_translate("Dialog", "Username"))
self.password_label.setText(_translate("Dialog", "Password"))
self.login_btn.setText(_translate("Dialog", "Login"))
self.signup_btn.setText(_translate("Dialog", "Sign Up"))
self.login_title.setText(_translate("Dialog", " Login"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QStackedWidget()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Dialog()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The main window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(593, 458)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(200, 180, 221, 71))
font = QtGui.QFont()
font.setPointSize(40)
self.label.setFont(font)
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.label.setText(_translate("MainWindow", "Welcome"))
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_())
and the signup page:
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
from welcome import Ui_MainWindow
import re
from PyQt5.QtWidgets import QMessageBox
class Ui_Dialog2(object):
def showMessageBox_password(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText("INVALID PASSWORD")
def showMessageBox_email(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText(" INVALID EMAIL")
def insertData(self):
username = self.username_entry.text()
password = self.password_entry.text()
email = self.email_entry.text()
connection = sqlite3.connect("login.db")
regex = '^(\w|\.|\_|\-)+[#](\w|\_|\-|\.)+[.]\w{2,3}$'
valid_email = True
valid_password = True
if(re.search(regex, email)):
valid_email = True
else:
valid_email = False
if len(password) > 7:
valid_password = True
else:
valid_password = False
if valid_email == True and valid_password == True:
connection.execute("INSERT INTO USERS VALUES(?,?,?)", (username, email, password))
connection.commit()
self.welcomewindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.welcomewindow)
self.welcomewindow.show()
if valid_email == False:
self.showMessageBox_email()
elif valid_password == False:
self.showMessageBox_password()
connection.close()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(593, 458)
self.user_name_label = QtWidgets.QLabel(Dialog)
self.user_name_label.setGeometry(QtCore.QRect(190, 200, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.user_name_label.sizePolicy().hasHeightForWidth())
self.user_name_label.setSizePolicy(sizePolicy)
self.user_name_label.setSizeIncrement(QtCore.QSize(0, 0))
self.user_name_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.user_name_label.setFont(font)
self.user_name_label.setObjectName("user_name_label")
self.password_label = QtWidgets.QLabel(Dialog)
self.password_label.setGeometry(QtCore.QRect(190, 240, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.password_label.sizePolicy().hasHeightForWidth())
self.password_label.setSizePolicy(sizePolicy)
self.password_label.setSizeIncrement(QtCore.QSize(0, 0))
self.password_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.password_label.setFont(font)
self.password_label.setObjectName("password_label")
self.email_label = QtWidgets.QLabel(Dialog)
self.email_label.setGeometry(QtCore.QRect(190, 160, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.email_label.sizePolicy().hasHeightForWidth())
self.email_label.setSizePolicy(sizePolicy)
self.email_label.setSizeIncrement(QtCore.QSize(0, 0))
self.email_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.email_label.setFont(font)
self.email_label.setObjectName("email_label")
self.email_entry = QtWidgets.QLineEdit(Dialog)
self.email_entry.setGeometry(QtCore.QRect(270, 160, 200, 20))
self.email_entry.setObjectName("email_entry")
self.username_entry = QtWidgets.QLineEdit(Dialog)
self.username_entry.setGeometry(QtCore.QRect(270, 200, 200, 20))
self.username_entry.setObjectName("username_entry")
self.password_entry = QtWidgets.QLineEdit(Dialog)
self.password_entry.setGeometry(QtCore.QRect(270, 240, 200, 20))
self.password_entry.setObjectName("password_entry")
self.password_entry.setEchoMode(self.password_entry.Password)
self.sign_up_button = QtWidgets.QPushButton(Dialog)
self.sign_up_button.setGeometry(QtCore.QRect(270, 280, 81, 31))
font = QtGui.QFont()
font.setPointSize(13)
self.sign_up_button.setFont(font)
self.sign_up_button.setObjectName("sign_up_button")
self.sign_up_button.clicked.connect(self.insertData)
self.login_title = QtWidgets.QLabel(Dialog)
self.login_title.setGeometry(QtCore.QRect(220, 50, 191, 71))
font = QtGui.QFont()
font.setPointSize(20)
self.login_title.setFont(font)
self.login_title.setObjectName("login_title")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(170, 360, 251, 31))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Sign Up Page"))
self.user_name_label.setText(_translate("Dialog", "Username"))
self.password_label.setText(_translate("Dialog", "Password"))
self.email_label.setText(_translate("Dialog", "Email"))
self.sign_up_button.setText(_translate("Dialog", "Sign Up"))
self.login_title.setText(_translate("Dialog", "Create Account"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Dialog2()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I want to automatically popup to another window,for test ,i add a buttom in my GUI,but there is nothing happened.What's more ,i do not want my thread killed,because it has happened before.How can I recorrecct my code?
main.py
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import time
from alert import Ui_Dialog
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(560, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(70, 60, 121, 41))
self.pushButton_3.setObjectName("pushButton_3")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
self.pushButton_2.setText(_translate("Control_system", "停止"))
self.pushButton_3.setText(_translate("Control_system", "跳转"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton_3.clicked.connect(self.jump_to_alert)
#QtCore.pyqtSlot()
def jump_to_alert(self):
self.popup_window_thread = PopupWindow(self)
self.popup_window_thread.start()
class Alert(QtWidgets.QDialog,Ui_Dialog):
def __init__(self):
QtWidgets.QDialog.__init__(self)
self.alert=Ui_Dialog()
self.alert.setupUi(self)
def closeEvent(self, event):
reply = QtWidgets.QMessageBox.question(self,
'警告',
"是否要退出警告?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
event.accept()
else:
event.ignore()
class PopupWindow(QtCore.QThread):
def __init__(self, parent=None):
super(PopupWindow, self).__init__()
self.index = 0
def run(self):
self.index+=1
while self.index <= 3:
alert = Alert()
alert.show()
alert.exec()
time.sleep(1)
def stop(self):
self.quit()
self.wait()
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
w = Control_system()
w.show()
app.exec()
this is another UI,which will popup to
alert.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(557, 444)
Dialog.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
Dialog.setWindowIcon(QIcon('images/icon.png'))
self.textBrowser = QtWidgets.QTextBrowser(Dialog)
self.textBrowser.setGeometry(QtCore.QRect(200, 80, 256, 41))
self.textBrowser.setObjectName("textBrowser")
self.textBrowser_2 = QtWidgets.QTextBrowser(Dialog)
self.textBrowser_2.setGeometry(QtCore.QRect(200, 170, 256, 41))
self.textBrowser_2.setObjectName("textBrowser_2")
self.textBrowser_3 = QtWidgets.QTextBrowser(Dialog)
self.textBrowser_3.setGeometry(QtCore.QRect(200, 260, 256, 41))
self.textBrowser_3.setObjectName("textBrowser_3")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(60, 80, 111, 31))
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(255, 0, 0);")
self.label.setTextFormat(QtCore.Qt.AutoText)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(Dialog)
self.label_2.setGeometry(QtCore.QRect(60, 170, 111, 31))
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setStyleSheet("color: rgb(255, 0, 0);")
self.label_2.setTextFormat(QtCore.Qt.AutoText)
self.label_2.setObjectName("label_2")
self.alert = QtWidgets.QLabel(Dialog)
self.alert.setGeometry(QtCore.QRect(60, 260, 111, 31))
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.alert.setFont(font)
self.alert.setStyleSheet("color: rgb(255, 0, 0);")
self.alert.setTextFormat(QtCore.Qt.AutoText)
self.alert.setObjectName("alert")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "警告"))
self.label.setText(_translate("Dialog", "报警车间"))
self.label_2.setText(_translate("Dialog", "报警机器"))
self.alert.setText(_translate("Dialog", "报警项目"))
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import time
from alert import Ui_Dialog
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(560, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(70, 60, 121, 41))
self.pushButton_3.setObjectName("pushButton_3")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
self.pushButton_2.setText(_translate("Control_system", "停止"))
self.pushButton_3.setText(_translate("Control_system", "跳转"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton_3.clicked.connect(self.jump_to_alert)
#QtCore.pyqtSlot()
def jump_to_alert(self):
self.popup_window_thread = PopupWindow(self)
self.popup_window_thread.popup.connect(self.goAlert) # +++
self.popup_window_thread.start()
def goAlert(self): # +++
self.alert = Alert()
self.alert.show()
class Alert(QtWidgets.QDialog,Ui_Dialog):
def __init__(self):
QtWidgets.QDialog.__init__(self)
self.alert=Ui_Dialog()
self.alert.setupUi(self)
def closeEvent(self, event):
reply = QtWidgets.QMessageBox.question(self,
'警告',
"是否要退出警告?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
event.accept()
else:
event.ignore()
class PopupWindow(QtCore.QThread):
popup = pyqtSignal() # +++
def __init__(self, parent=None):
super(PopupWindow, self).__init__()
self.index = 0
def run(self):
# self.index+=1
self.popup.emit() # +++
while self.index <= 3:
# alert = Alert()
# alert.show()
# alert.exec()
self.index += 1 # +++
time.sleep(1)
def stop(self):
self.quit()
self.wait()
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
w = Control_system()
w.show()
app.exec()
i want to create a progress bar showing(as busy) until the code of a button ends .My target is to show it when button(connected to function) pressed ,stay visible as code runs , and hide it when the function connected to the button ends.This task is done partially but my progress bar setVisible(True) waits until code ends and they show.
My code is here:
from ui import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
from PyQt5.QtWidgets import QDialog,QWidget,QApplication, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtGui import QIcon
class ProgressThread(QtCore.QThread):
job_done = QtCore.pyqtSignal('QString')
def __init__(self, parent=None):
super(ProgressThread, self).__init__(parent)
self.gui_bar = None
def do_work(self):
self.job_done.emit(self.gui_bar)
def run(self):
self.do_work()
class mainProgram(QtWidgets.QMainWindow, Ui_MainWindow): #main window
def __init__(self, parent=None):
super(mainProgram, self).__init__(parent)
self.setupUi(self)
self.progress_thread = ProgressThread()
self.progress_thread.job_done.connect(self.on_job_start)
self.create_ui()
self.B_aerodrome_data.clicked.connect(self.start_thread)
self.B_aerodrome_data.clicked.connect(self.aerodrome_data)
def aerodrome_data(self): #def i want with start show progress bar
#here show progressBar(self.progress.setVisible(True) and update gui)
#do many staffs of code here that takes time
#here hide progress bar and update gui
def start_thread(self):
self.progress_thread.gui_bar = self.progress.setVisible(False)
self.progress_thread.start()
def on_job_done(self):
print("Generated string : ")
self.progress.setVisible(False)
def on_job_start(self):
print("aaaaaaaaaa")
self.progress.setRange(0,0)
self.progress.setVisible(True)
def create_ui(self):
self.progress = QtWidgets.QProgressBar(self)
self.progress.setVisible(False)
self.progress.setGeometry(200, 205, 250, 20)
self.progress.setRange(0, 0)
self.progress.setObjectName("progress")
#self.button.clicked.connect(self.start_thread)
layout = QtWidgets.QVBoxLayout(self)
#layout.addWidget(self.button)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
nextGui = mainProgram()
nextGui.showMaximized()
sys.exit(app.exec_())
The Ui_Mainwindow is here:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1371, 924)
MainWindow.setAcceptDrops(True)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("images/356.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(True)
MainWindow.setDocumentMode(True)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.L_adinput = QtWidgets.QLabel(self.centralWidget)
self.L_adinput.setGeometry(QtCore.QRect(30, 70, 141, 31))
self.L_adinput.setObjectName("L_adinput")
# self.progress = QtWidgets.QProgressBar(self)
# self.progress.setGeometry(200, 205, 250, 20)
# self.progress.setProperty("value", 0)
# self.progress.setObjectName("progress")
self.L_progress = QtWidgets.QLabel(self.centralWidget)
self.L_progress.setGeometry(QtCore.QRect(150, 200, 141, 31))
self.L_progress.setObjectName("L_progress")
self.B_aerodrome_data = QtWidgets.QPushButton(self.centralWidget)
self.B_aerodrome_data.setGeometry(QtCore.QRect(670, 100, 271, 41))
self.B_aerodrome_data.setObjectName("B_aerodrome_data")
self.T_aerodrome_ouput = QtWidgets.QTextEdit(self.centralWidget)
self.T_aerodrome_ouput.setGeometry(QtCore.QRect(30, 230, 561, 371))
self.T_aerodrome_ouput.setReadOnly(True)
self.T_aerodrome_ouput.setObjectName("T_aerodrome_ouput")
self.B_alternates = QtWidgets.QPushButton(self.centralWidget)
self.B_alternates.setGeometry(QtCore.QRect(670, 160, 271, 41))
self.B_alternates.setObjectName("B_alternates")
self.B_weather = QtWidgets.QPushButton(self.centralWidget)
self.B_weather.setGeometry(QtCore.QRect(670, 220, 271, 41))
self.B_weather.setObjectName("B_weather")
self.B_fuel = QtWidgets.QPushButton(self.centralWidget)
self.B_fuel.setEnabled(True)
self.B_fuel.setGeometry(QtCore.QRect(1050, 100, 271, 41))
self.B_fuel.setObjectName("B_fuel")
self.set_path1 = QtWidgets.QPushButton(self.centralWidget)
self.set_path1.setEnabled(True)
self.set_path1.setGeometry(QtCore.QRect(1100, 160, 101, 31))
self.set_path1.setObjectName("set_path1")
self.set_path2 = QtWidgets.QPushButton(self.centralWidget)
self.set_path2.setEnabled(True)
self.set_path2.setGeometry(QtCore.QRect(1100, 210, 101, 31))
self.set_path2.setObjectName("set_path2")
self.set_path3 = QtWidgets.QPushButton(self.centralWidget)
self.set_path3.setEnabled(True)
self.set_path3.setGeometry(QtCore.QRect(1100, 260, 101, 31))
self.set_path3.setObjectName("set_path3")
self.set_path4 = QtWidgets.QPushButton(self.centralWidget)
self.set_path4.setEnabled(True)
self.set_path4.setGeometry(QtCore.QRect(1100, 310, 101, 31))
self.set_path4.setObjectName("set_path4")
self.set_path5 = QtWidgets.QPushButton(self.centralWidget)
self.set_path5.setEnabled(True)
self.set_path5.setGeometry(QtCore.QRect(1100, 360, 101, 31))
self.set_path5.setObjectName("set_path5")
self.tool1 = QtWidgets.QToolButton(self.centralWidget)
self.tool1.setGeometry(QtCore.QRect(1240, 170, 25, 19))
self.tool1.setObjectName("tool1")
self.tool2 = QtWidgets.QToolButton(self.centralWidget)
self.tool2.setGeometry(QtCore.QRect(1240, 220, 25, 20))
self.tool2.setObjectName("tool2")
self.tool3 = QtWidgets.QToolButton(self.centralWidget)
self.tool3.setGeometry(QtCore.QRect(1240, 270, 25, 19))
self.tool3.setObjectName("tool3")
self.tool4 = QtWidgets.QToolButton(self.centralWidget)
self.tool4.setGeometry(QtCore.QRect(1240, 320, 25, 19))
self.tool4.setObjectName("tool4")
self.tool1x = QtWidgets.QToolButton(self.centralWidget)
self.tool1x.setGeometry(QtCore.QRect(1280, 220, 25, 19))
self.tool1x.setObjectName("tool1x")
self.tool2x = QtWidgets.QToolButton(self.centralWidget)
self.tool2x.setGeometry(QtCore.QRect(1280, 270, 25, 19))
self.tool2x.setObjectName("tool2x")
self.tool3x = QtWidgets.QToolButton(self.centralWidget)
self.tool3x.setGeometry(QtCore.QRect(1280, 320, 25, 19))
self.tool3x.setObjectName("tool3x")
self.tool4x = QtWidgets.QToolButton(self.centralWidget)
self.tool4x.setGeometry(QtCore.QRect(1280, 370, 25, 19))
self.tool4x.setObjectName("tool4x")
self.line = QtWidgets.QFrame(self.centralWidget)
self.line.setGeometry(QtCore.QRect(990, -50, 20, 851))
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.T_aerodromes_input = QtWidgets.QTextEdit(self.centralWidget)
self.T_aerodromes_input.setGeometry(QtCore.QRect(30, 100, 331, 71))
self.T_aerodromes_input.setStyleSheet("font: 10pt \"MS Shell Dlg 2\";")
self.T_aerodromes_input.setObjectName("T_aerodromes_input")
self.label = QtWidgets.QLabel(self.centralWidget)
self.label.setGeometry(QtCore.QRect(30, 200, 161, 31))
self.label.setObjectName("label")
self.B_print = QtWidgets.QPushButton(self.centralWidget)
self.B_print.setGeometry(QtCore.QRect(530, 230, 41, 31))
self.B_print.setText("")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("images/printer.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.B_print.setIcon(icon1)
self.B_print.setIconSize(QtCore.QSize(41, 31))
self.B_print.setObjectName("B_print")
self.B_clear = QtWidgets.QPushButton(self.centralWidget)
self.B_clear.setGeometry(QtCore.QRect(490, 230, 41, 31))
self.B_clear.setText("")
self.label_2 = QtWidgets.QLabel(self.centralWidget)
self.label_2.setGeometry(QtCore.QRect(670, 30, 271, 41))
self.label_2.setStyleSheet("font: 75 11pt \"MS Shell Dlg 2\";")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(self.centralWidget)
self.label_3.setGeometry(QtCore.QRect(1050, 30, 271, 41))
self.label_3.setStyleSheet("font: 75 11pt \"MS Shell Dlg 2\";")
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("images/clear.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.B_clear.setIcon(icon2)
self.B_clear.setIconSize(QtCore.QSize(41, 31))
self.B_clear.setObjectName("B_clear")
self.L_adinput.raise_()
self.L_progress.raise_()
self.B_aerodrome_data.raise_()
self.T_aerodrome_ouput.raise_()
self.B_alternates.raise_()
self.B_weather.raise_()
self.B_fuel.raise_()
self.set_path2.raise_()
self.set_path3.raise_()
self.set_path4.raise_()
self.set_path5.raise_()
self.tool1.raise_()
self.set_path1.raise_()
self.tool2.raise_()
self.tool3.raise_()
self.tool4.raise_()
self.tool1x.raise_()
self.tool2x.raise_()
self.tool3x.raise_()
self.tool4x.raise_()
self.line.raise_()
self.T_aerodromes_input.raise_()
self.label.raise_()
self.B_print.raise_()
self.B_clear.raise_()
self.label_2.raise_()
self.label_3.raise_()
MainWindow.setCentralWidget(self.centralWidget)
self.retranslateUi(MainWindow)
self.tool1.clicked.connect(self.tool2.show)
self.tool1.clicked.connect(self.set_path2.show)
self.tool2.clicked.connect(self.tool3.show)
self.tool3.clicked.connect(self.tool4.show)
self.tool3.clicked.connect(self.set_path4.show)
self.tool4.clicked.connect(self.set_path5.show)
self.tool2.clicked.connect(self.set_path3.show)
self.tool4x.clicked.connect(self.set_path5.hide)
self.tool3x.clicked.connect(self.tool4.hide)
self.tool3x.clicked.connect(self.set_path4.hide)
self.tool2x.clicked.connect(self.tool3.hide)
self.tool2x.clicked.connect(self.set_path3.hide)
self.tool1x.clicked.connect(self.tool2.hide)
self.tool1x.clicked.connect(self.set_path2.hide)
self.tool4x.clicked.connect(self.tool4x.hide)
self.tool3x.clicked.connect(self.tool3x.hide)
self.tool2x.clicked.connect(self.tool2x.hide)
self.tool1x.clicked.connect(self.tool1x.hide)
self.tool1.clicked.connect(self.tool1x.show)
self.tool2.clicked.connect(self.tool2x.show)
self.tool3.clicked.connect(self.tool3x.show)
self.tool4.clicked.connect(self.tool4x.show)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Planner"))
self.L_adinput.setText(_translate("MainWindow", "ICAO LOCATORS"))
self.L_progress.setText(_translate("MainWindow", "Progress"))
self.B_aerodrome_data.setText(_translate("MainWindow", "AERODROME DATA"))
# self.T_aerodrome_ouput.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
# "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
# "p, li { white-space: pre-wrap; }\n"
# "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
# "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p></body></html>"))
self.B_alternates.setText(_translate("MainWindow", "ALTERNATES XLSX"))
self.B_weather.setText(_translate("MainWindow", "WEATHER BRIEFING"))
self.B_fuel.setText(_translate("MainWindow", "FUEL XLSX"))
self.set_path1.setText(_translate("MainWindow", "SET FORM"))
self.set_path2.setText(_translate("MainWindow", "SET FORM"))
self.set_path3.setText(_translate("MainWindow", "SET FORM"))
self.set_path4.setText(_translate("MainWindow", "SET FORM"))
self.set_path5.setText(_translate("MainWindow", "SET FORM"))
self.tool1.setText(_translate("MainWindow", "..."))
self.tool2.setText(_translate("MainWindow", "..."))
self.tool3.setText(_translate("MainWindow", "..."))
self.tool4.setText(_translate("MainWindow", "..."))
self.tool1x.setText(_translate("MainWindow", "X"))
self.tool2x.setText(_translate("MainWindow", "X"))
self.tool3x.setText(_translate("MainWindow", "X"))
self.tool4x.setText(_translate("MainWindow", "X"))
self.T_aerodromes_input.setPlaceholderText(_translate("MainWindow", "Set 4 character ICAO Locator here , divided by spaces..."))
self.label.setText(_translate("MainWindow", "OUTPUT"))
self.label_2.setText(_translate("MainWindow", "GENERAL"))
self.label_3.setText(_translate("MainWindow", "FUEL"))
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_())
In your case I see that you have created functions unnecessarily, I have eliminated some. According to what you tell me, it is not necessary for the signal to carry information, so I will create a signal without parameters. the slot connected to the button must make visible the QProgressBar and start the thread, and the signal job_done must connect with the method that hides the QProgressBar, in the following example use QThread::sleep() to emulate some processing.
class ProgressThread(QtCore.QThread):
job_done = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(ProgressThread, self).__init__(parent)
def do_work(self):
QtCore.QThread.sleep(2) # emulate processing
self.job_done.emit()
def run(self):
self.do_work()
class mainProgram(QtWidgets.QMainWindow, Ui_MainWindow): # main window
def __init__(self, parent=None):
super(mainProgram, self).__init__(parent)
self.setupUi(self)
self.progress_thread = ProgressThread()
self.progress_thread.job_done.connect(self.on_job_done)
self.create_ui()
self.B_aerodrome_data.clicked.connect(self.aerodrome_data)
def aerodrome_data(self):
self.start_thread()
def start_thread(self):
self.progress.setVisible(True)
self.progress_thread.start()
def on_job_done(self):
print("Generated string : ")
self.progress.setVisible(False)
def create_ui(self):
[...]
try this code, you will find your solution from here.
when you will press the button thread will start and emit int data to the progress bar from 0-100
from PyQt5.QtWidgets import QMainWindow,QWidget,QApplication,QVBoxLayout,QPushButton,QProgressBar
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt,QThread,pyqtSignal
import time
import sys
class THREAD(QThread): # QThread is use for parallal execution
EMIT=pyqtSignal(int)
def run(self):
count=0
while count<=100:
count+=1
self.EMIT.emit(count)
time.sleep(0.1)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.ICON="icon.jpg"
self.TITLE="ROBO Science LAB"
self.TOP = 100
self.LEFT = 100
self.WIDTH = 700
self.HEIGHT = 500
self.InitWindow()
self.setCentralWidget(ComponentManagement())
self.show()
def InitWindow(self):
self.setWindowIcon(QIcon(self.ICON))
self.setWindowTitle(self.TITLE)
self.setGeometry(self.TOP,self.LEFT,self.WIDTH,self.HEIGHT)
class ComponentManagement(QWidget):
def __init__(self):
super().__init__()
self.UIcomponent()
def UIcomponent(self):
vbox = QVBoxLayout()
self.progress1 = QProgressBar()
BUTTON = QPushButton("Click to start progress")
BUTTON.setStyleSheet("background:#E67E22")
BUTTON.clicked.connect(self.StartProgressBar)
vbox.addWidget(self.progress1)
vbox.addWidget(BUTTON)
self.setLayout(vbox)
def SetProgressValue(self, val):
self.progress1.setValue(val)
def StartProgressBar(self):
self.ThredObject = THREAD()
self.ThredObject.EMIT.connect(self.SetProgressValue)
self.ThredObject.start()
if __name__=="__main__":
App=QApplication(sys.argv)
window=Window()
sys.exit(App.exec())
i cannot go back to the first page of the stacked widget on, when i click the cancel button (from the cancel_button_clicked(self): function)
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
class Ui_form(object):
def setupUi(self, form):
form.setObjectName("form")
form.resize(1000, 650)
self.groupBox = QtWidgets.QGroupBox(form)
self.groupBox.setGeometry(QtCore.QRect(530, 350, 451, 281))
self.groupBox.setObjectName("groupBox")
self.stackedWidget = QtWidgets.QStackedWidget(self.groupBox)
self.stackedWidget.setGeometry(QtCore.QRect(9, 19, 431, 241))
self.stackedWidget.setObjectName("stackedWidget")
self.page_1 = QtWidgets.QWidget()
self.page_1.setObjectName("page_1")
self.login_button = QtWidgets.QPushButton(self.page_1)
self.login_button.setGeometry(QtCore.QRect(20, 210, 75, 23))
self.login_button.setObjectName("login_button")
self.register_button = QtWidgets.QPushButton(self.page_1)
self.register_button.setGeometry(QtCore.QRect(180, 210, 75, 23))
self.register_button.setObjectName("register_button")
self.exit_button = QtWidgets.QPushButton(self.page_1)
self.exit_button.setGeometry(QtCore.QRect(330, 210, 75, 23))
self.exit_button.setObjectName("exit_button")
self.username_line = QtWidgets.QLineEdit(self.page_1)
self.username_line.setGeometry(QtCore.QRect(230, 40, 113, 20))
self.username_line.setObjectName("username_line")
self.password_line = QtWidgets.QLineEdit(self.page_1)
self.password_line.setGeometry(QtCore.QRect(230, 110, 113, 20))
self.password_line.setObjectName("password_line")
self.username_label = QtWidgets.QLabel(self.page_1)
self.username_label.setGeometry(QtCore.QRect(60, 40, 81, 16))
self.username_label.setObjectName("username_label")
self.password_label = QtWidgets.QLabel(self.page_1)
self.password_label.setGeometry(QtCore.QRect(60, 110, 61, 16))
self.password_label.setObjectName("password_label")
self.stackedWidget.addWidget(self.page_1)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.registeruser_label = QtWidgets.QLabel(self.page_2)
self.registeruser_label.setGeometry(QtCore.QRect(60, 33, 71, 20))
self.registeruser_label.setObjectName("registeruser_label")
self.registerepass_label = QtWidgets.QLabel(self.page_2)
self.registerepass_label.setGeometry(QtCore.QRect(60, 100, 61, 16))
self.registerepass_label.setObjectName("registerepass_label")
self.registeruser_line = QtWidgets.QLineEdit(self.page_2)
self.registeruser_line.setGeometry(QtCore.QRect(240, 40, 113, 20))
self.registeruser_line.setObjectName("registeruser_line")
self.registerpass_line = QtWidgets.QLineEdit(self.page_2)
self.registerpass_line.setGeometry(QtCore.QRect(240, 100, 113, 20))
self.registerpass_line.setObjectName("registerpass_line")
self.signup_button = QtWidgets.QPushButton(self.page_2)
self.signup_button.setGeometry(QtCore.QRect(70, 190, 75, 23))
self.signup_button.setObjectName("signup_button")
self.cancel_button = QtWidgets.QPushButton(self.page_2)
self.cancel_button.setGeometry(QtCore.QRect(270, 190, 75, 23))
self.cancel_button.setObjectName("cancel_button")
self.stackedWidget.addWidget(self.page_2)
self.retranslateUi(form)
self.stackedWidget.setCurrentIndex(0)
self.login_button.clicked.connect(self.login_button_clicked)
self.register_button.clicked.connect(self.register_button_clicked)
self.cancel_button.clicked.connect(self.cancel_button_clicked)
self.exit_button.clicked.connect(self.exit_button_clicked)
def retranslateUi(self, form):
_translate = QtCore.QCoreApplication.translate
form.setWindowTitle(_translate("form", "Form"))
self.groupBox.setTitle(_translate("form", "USER"))
self.login_button.setText(_translate("form", "LOG IN"))
self.register_button.setText(_translate("form", "REGISTER"))
self.exit_button.setText(_translate("form", "EXIT"))
self.username_label.setText(_translate("form", "USERNAME"))
self.password_label.setText(_translate("form", "PASSWORD"))
self.registeruser_label.setText(_translate("form", "USERNAME"))
self.registerepass_label.setText(_translate("form", "PASSWORD"))
self.signup_button.setText(_translate("form", "SIGN UP"))
self.cancel_button.setText(_translate("form", "CANCEL"))
def login_button_clicked(self):
file = open('user.txt','r')
for line in file:
us, pa = line.rstrip().split(';')
if self.username_line.text() == us and self.password_line.text() == pa:
QMessageBox.information(QMessageBox(), "Login", "LOGIN SUCCESS!")
break
else:
QMessageBox.information(QMessageBox(), "login", "LOGIN FAILED!")
def register_button_clicked(self):
self.stackedWidget.setCurrentIndex(1)
def cancel_button_clicked(self):
self.stackedWidget.setCurrentIndex(-1)
def exit_button_clicked(self):
self.close()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
LOGIN_window = QtWidgets.QDialog()
LOGIN = Ui_form()
LOGIN.setupUi(LOGIN_window)
LOGIN_window.show()
sys.exit(app.exec_())
It is not advisable to modify the class that Qt Designer generates, and worse if you are a beginner. The most recommended is to create a class that implements logic and use the design already created.
To do this you must choose the appropriate Widget, if you used as a template to MainWindow you should use QMainWindow, if you use Widget you must use QWidget and if you use any of the variants of Dialog you should use QDialog as I think this is the case.
Since the task is simple it is not necessary to create a method like slot, we could use a lambda function: lambda: self.stackedWidget.setCurrentIndex(1)
All of the above I implemented in the following code:
class Dialog(QtWidgets.QDialog, Ui_form):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
self.stackedWidget.setCurrentIndex(0)
self.login_button.clicked.connect(self.Confirm_Button_Clicked)
self.register_button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))
self.cancel_button.clicked.connect(self.cancel_button_clicked)
def Confirm_Button_Clicked(self):
file = open('user.txt','r')
[...]
def cancel_button_clicked(self):
self.stackedWidget.setCurrentIndex(0)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
Note: If you want to return to the first page you should place the value of 0 as the current index, remember that the indexes start from 0.
I have a problem displaying the output of a function in a qdialog of pyqt.
My code is as follows:
import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue
start_time = time.time()
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit
noreports = len(glob.glob('*.txt'))
class Dialogo(QDialog):
def __init__(self):
QDialog.__init__(self)
self.resize(400, 380)
self.nombre = QLabel(self)
self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
self.nombre.setObjectName("nombre")
self.label = QLabel(self)
self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
self.label.setObjectName("label")
self.pushButton = QPushButton(self)
self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
self.pushButton.setObjectName("pushButton")
self.scrollArea = QScrollArea(self)
self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.progressBar = QProgressBar(self)
self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.textEdit = QTextEdit(self)
self.scrollArea.setWidget(self.textEdit)
self.retranslateUi(self)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, Dialogo):
global noreports
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("Dialog", "Process..."))
self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
self.pushButton.setText(_translate("Dialog", "Terminate"))
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(321, 247)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Form.setWindowIcon(icon)
Form.setWindowOpacity(0.98)
Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
self.lineEdit.setAutoFillBackground(True)
self.lineEdit.setObjectName("lineEdit")
self.DescriptLbl = QtWidgets.QLabel(Form)
self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
self.DescriptLbl.setObjectName("DescriptLbl")
self.showinformBtn = QtWidgets.QPushButton(Form)
self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.showinformBtn.setObjectName("showinformBtn")
self.dialogo = Dialogo()
self.showinformBtn.clicked.connect(self.abrirDialogo)
#self.showinformBtn.clicked.connect(self.showinform)
self.CancelarBtn = QtWidgets.QPushButton(Form)
self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.CancelarBtn.setObjectName("CancelarBtn")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
self.label_2.setTextFormat(QtCore.Qt.RichText)
self.label_2.setScaledContents(True)
self.label_2.setOpenExternalLinks(True)
self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
self.label_2.setObjectName("label_2")
self.showinformLbl = QtWidgets.QLabel(Form)
self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
font = QtGui.QFont()
font.setPointSize(22)
self.showinformLbl.setFont(font)
self.showinformLbl.setObjectName("showinformLbl")
self.imagen = QtWidgets.QLabel(Form)
self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
self.imagen.setText("")
self.imagen.setPixmap(QtGui.QPixmap("max.png"))
self.imagen.setScaledContents(False)
self.imagen.setIndent(-1)
self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.imagen.setObjectName("imagen")
self.imagen.raise_()
self.lineEdit.raise_()
self.DescriptLbl.raise_()
self.showinformBtn.raise_()
self.CancelarBtn.raise_()
self.label_2.raise_()
self.showinformLbl.raise_()
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "api-server"))
self.lineEdit.setToolTip(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.lineEdit.setWhatsThis(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.DescriptLbl.setText(_translate("Form", "descrip inform."))
self.showinformBtn.setToolTip(_translate("Form", "<html><head/><body><p>Create report.</p></body></html>"))
self.showinformBtn.setText(_translate("Form", "show inform"))
self.CancelarBtn.setToolTip(_translate("Form", "<html><head/><body><p>Cancel.</p></body></html>"))
self.CancelarBtn.setText(_translate("Form", "Cancel"))
self.label_2.setText(_translate("Form", "<html><head/><body><p>Visit api-server. ;)</p></body></html>"))
self.showinformLbl.setText(_translate("Form", "show inform."))
def abrirDialogo(self):
nombreinform = self.lineEdit.text()
self.dialogo.nombre.setText('inform:' + nombreinform)
self.dialogo.show()
self.showinform()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", format(avance))
self.dialogo.textEdit.setText(file + format(avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
The code is executed but not displayed in Dialog, only the labels but not the progress bar.
Why does this happen?
The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.
The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.
If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", avance)
self.dialogo.textEdit.append("{}{}".format(file, avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
QApplication.processEvents()
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.
Instead of using setProperty you could use the setValue function of QProgressBar:
self.dialogo.progressBar.setValue(avance)
Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.