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())
Related
I am trying to load my homescreen after the splashscreen. Upon running the code, the splashscreen manages to load but it stops there. How do I fix this?
This is my SplashScreen class
class SplashScreen(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(700, 350)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.counter = 0
self.n = 100
self.initUI()
self.timer = QTimer()
self.timer.timeout.connect(self.loading)
self.timer.start(30)
def initUI(self):
# layout to display splash scrren frame
layout = QVBoxLayout()
self.setLayout(layout)
# splash screen frame
self.frame = QFrame()
layout.addWidget(self.frame)
# splash screen title
self.title_label = QLabel(self.frame)
self.title_label.setObjectName('title_label')
self.title_label.resize(690, 120)
self.title_label.move(0, 5) # x, y
self.title_label.setText('Splash Screen')
self.title_label.setAlignment(Qt.AlignCenter)
# splash screen title description
self.description_label = QLabel(self.frame)
self.description_label.resize(690, 40)
self.description_label.move(0, self.title_label.height())
self.description_label.setObjectName('desc_label')
self.description_label.setText('<b>Splash Screen PyQt-5</b>')
self.description_label.setAlignment(Qt.AlignCenter)
# splash screen pogressbar
self.progressBar = QProgressBar(self.frame)
self.progressBar.resize(self.width() - 200 - 10, 50)
self.progressBar.move(100, 180) # self.description_label.y()+130
self.progressBar.setAlignment(Qt.AlignCenter)
self.progressBar.setFormat('%p%')
self.progressBar.setTextVisible(True)
self.progressBar.setRange(0, self.n)
self.progressBar.setValue(20)
# spash screen loading label
self.loading_label = QLabel(self.frame)
self.loading_label.resize(self.width() - 10, 50)
self.loading_label.move(0, self.progressBar.y() + 70)
self.loading_label.setObjectName('loading_label')
self.loading_label.setAlignment(Qt.AlignCenter)
self.loading_label.setText('Loading...')
This is the function that lets the splashscreen load and launch the WindowApp class but it does not work. What I mean by does not work I meant that it does not load the WindowApp. It just closes.
def loading(self):
# set progressbar value
self.progressBar.setValue(self.counter)
# stop progress if counter
# is greater than n and
# display main window app
if self.counter >= self.n:
self.timer.stop()
self.close()
MainWindow = QtWidgets.QMainWindow()
ui = WindowApp()
ui.setupUi(MainWindow)
MainWindow.show()
self.counter += 1
This is my main window
class WindowApp(QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1006, 654)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 10, 981, 641))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
self.label.setFont(font)
self.label.setText("")
self.label.setPixmap(QtGui.QPixmap("../pygui/Homescreen.png"))
self.label.setScaledContents(True)
self.label.setWordWrap(False)
self.label.setObjectName("label")
self.infoBtn = QtWidgets.QPushButton(self.centralwidget)
self.infoBtn.setGeometry(QtCore.QRect(120, 550, 181, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(15)
self.infoBtn.setFont(font)
self.infoBtn.setStyleSheet("border-radius: 10px;\n"
"border-color: 2px solid gray;\n"
"background-color: rgb(255, 255, 255);")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icons/info_icon.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.infoBtn.setIcon(icon)
self.infoBtn.setObjectName("infoBtn")
self.startBtn = QtWidgets.QPushButton(self.centralwidget)
self.startBtn.setGeometry(QtCore.QRect(310, 270, 431, 111))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(28)
self.startBtn.setFont(font)
self.startBtn.setStyleSheet("background-color: #305E6C;\n"
"color: white;\n"
"border-radius: 10px;\n"
"border: 2px solid white")
self.startBtn.setObjectName("startBtn")
self.contactsBtn = QtWidgets.QPushButton(self.centralwidget)
self.contactsBtn.setGeometry(QtCore.QRect(720, 30, 101, 101))
self.contactsBtn.setStyleSheet("\n"
"background-color: #121212;\n"
"border-radius: 50%;\n"
"border: 2px solid white;")
self.contactsBtn.setText("")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("icons/typcn_contacts.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.contactsBtn.setIcon(icon1)
self.contactsBtn.setIconSize(QtCore.QSize(40, 40))
self.contactsBtn.setObjectName("contactsBtn")
self.dateBtn = QtWidgets.QPushButton(self.centralwidget)
self.dateBtn.setGeometry(QtCore.QRect(840, 30, 101, 101))
self.dateBtn.setStyleSheet("\n"
"background-color: #121212;\n"
"border-radius: 50%;\n"
"border: 2px solid white;")
self.dateBtn.setText("")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("icons/Group.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.dateBtn.setIcon(icon2)
self.dateBtn.setIconSize(QtCore.QSize(40, 40))
self.dateBtn.setObjectName("dateBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1006, 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)
self.infoBtn.clicked.connect(partial(self.show_popup))
self.dateBtn.clicked.connect(self.openDateWindow)
self.startBtn.clicked.connect(self.openDriveWindow)
self.contactsBtn.clicked.connect(self.openContactWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.infoBtn.setText(_translate("MainWindow", "About"))
self.startBtn.setText(_translate("MainWindow", "Driving Mode"))
def show_popup(self):
msg = QMessageBox()
msg.setWindowTitle('About Us')
msg.setText('Testing')
msg.setIcon(QMessageBox.Information)
x = msg.exec_()
def openDateWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_DateWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
def openDriveWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_DriveWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
def openContactWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_ContactWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
I have tried changing this to WindowApp() just to check if the MainWindow has any problems but it manages to load without the splashscreen.
app = QApplication(sys.argv)
splash = SplashScreen()
splash.show()
sys.exit(app.exec_())
Check my answer from this previous post that I think will help you.
You can show the splash screen and when the splash screen closes then you can show your main window. It's similar to the login window from this previous question
But if you want to keep implementing your code the way you have it I think I know the problem.
You call a method which creates the QMainWindow and calls the .show() for that QMainWindow. Once the method is done the variables in that method are garbage collected and so is your QMainWindow object. The way to keep the reference and prevent those variables from getting garbage collected is by making it a class variable by adding self. in front of the variable.
I would maybe restructure a bit and do something like this:
if __name__ == "__main__":
app = QApplication(sys.argv)
splash = SplashScreen()
splash_closed = splash.exec_()
if splash_closed:
window = WindowApp()
window.show()
sys.exit(app.exec_())
Where the splashscreen is now a QDialog and when you're done loading you close the dialog with self.accept() instead of trying to show a new window:
class SplashScreen(QDialog):
def __init__(self):
super().__init__()
self.setFixedSize(700, 350)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.counter = 0
self.n = 100
self.initUI()
self.timer = QTimer()
self.timer.timeout.connect(self.loading)
self.timer.start(30)
def initUI(self):
...
def loading(self):
# set progressbar value
self.progressBar.setValue(self.counter)
# stop progress if counter
# is greater than n and
# display main window app
if self.counter >= self.n:
self.timer.stop()
self.accept()
self.counter += 1
And you should also use the __init__ method on your main window and maybe move all the self.setupUI code in there, or just do something like this:
class WindowApp(QMainWindow):
def __init__(self):
QtWidgets.QDialog.__init__(self)
self.setupUi(self)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1006, 654)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
Hope this helps
import sys
from PyQt5.QtWidgets import QMainWindow, QDialog, QApplication
from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QFrame, QLabel, QProgressBar
from PyQt5.QtWidgets import QWidget
from PyQt5 import QtCore, QtGui
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QTimer
class SplashScreen(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(700, 350)
self.setWindowFlag(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.counter = 0
self.n = 100
self.initUI()
self.timer = QTimer()
self.timer.timeout.connect(self.loading)
self.timer.start(30)
def initUI(self):
# layout to display splash scrren frame
layout = QVBoxLayout()
self.setLayout(layout)
# splash screen frame
self.frame = QFrame()
layout.addWidget(self.frame)
# splash screen title
self.title_label = QLabel(self.frame)
self.title_label.setObjectName('title_label')
self.title_label.resize(690, 120)
self.title_label.move(0, 5) # x, y
self.title_label.setText('Splash Screen')
self.title_label.setAlignment(Qt.AlignCenter)
# splash screen title description
self.description_label = QLabel(self.frame)
self.description_label.resize(690, 40)
self.description_label.move(0, self.title_label.height())
self.description_label.setObjectName('desc_label')
self.description_label.setText('<b>Splash Screen PyQt-5</b>')
self.description_label.setAlignment(Qt.AlignCenter)
# splash screen pogressbar
self.progressBar = QProgressBar(self.frame)
self.progressBar.resize(self.width() - 200 - 10, 50)
self.progressBar.move(100, 180) # self.description_label.y()+130
self.progressBar.setAlignment(Qt.AlignCenter)
self.progressBar.setFormat('%p%')
self.progressBar.setTextVisible(True)
self.progressBar.setRange(0, self.n)
self.progressBar.setValue(20)
# spash screen loading label
self.loading_label = QLabel(self.frame)
self.loading_label.resize(self.width() - 10, 50)
self.loading_label.move(0, self.progressBar.y() + 70)
self.loading_label.setObjectName('loading_label')
self.loading_label.setAlignment(Qt.AlignCenter)
self.loading_label.setText('Loading...')
self.show()
def loading(self):
# set progressbar value
self.progressBar.setValue(self.counter)
# stop progress if counter
# is greater than n and
# display main window app
if self.counter >= self.n:
self.timer.stop()
'''
self.close()
MainWindow = QtWidgets.QMainWindow()
ui = WindowApp()
ui.setupUi(MainWindow)
MainWindow.show()
'''
self.ui = WindowApp()
self.ui.show()
self.close()
self.counter += 1
class WindowApp(QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1006, 654)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 10, 981, 641))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(10)
self.label.setFont(font)
self.label.setText("")
self.label.setPixmap(QtGui.QPixmap("../pygui/Homescreen.png"))
self.label.setScaledContents(True)
self.label.setWordWrap(False)
self.label.setObjectName("label")
self.infoBtn = QtWidgets.QPushButton(self.centralwidget)
self.infoBtn.setGeometry(QtCore.QRect(120, 550, 181, 41))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(15)
self.infoBtn.setFont(font)
self.infoBtn.setStyleSheet("border-radius: 10px;\n"
"border-color: 2px solid gray;\n"
"background-color: rgb(255, 255, 255);")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("icons/info_icon.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.infoBtn.setIcon(icon)
self.infoBtn.setObjectName("infoBtn")
self.startBtn = QtWidgets.QPushButton(self.centralwidget)
self.startBtn.setGeometry(QtCore.QRect(310, 270, 431, 111))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(28)
self.startBtn.setFont(font)
self.startBtn.setStyleSheet("background-color: #305E6C;\n"
"color: white;\n"
"border-radius: 10px;\n"
"border: 2px solid white")
self.startBtn.setObjectName("startBtn")
self.contactsBtn = QtWidgets.QPushButton(self.centralwidget)
self.contactsBtn.setGeometry(QtCore.QRect(720, 30, 101, 101))
self.contactsBtn.setStyleSheet("\n"
"background-color: #121212;\n"
"border-radius: 50%;\n"
"border: 2px solid white;")
self.contactsBtn.setText("")
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap("icons/typcn_contacts.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.contactsBtn.setIcon(icon1)
self.contactsBtn.setIconSize(QtCore.QSize(40, 40))
self.contactsBtn.setObjectName("contactsBtn")
self.dateBtn = QtWidgets.QPushButton(self.centralwidget)
self.dateBtn.setGeometry(QtCore.QRect(840, 30, 101, 101))
self.dateBtn.setStyleSheet("\n"
"background-color: #121212;\n"
"border-radius: 50%;\n"
"border: 2px solid white;")
self.dateBtn.setText("")
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap("icons/Group.png"),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.dateBtn.setIcon(icon2)
self.dateBtn.setIconSize(QtCore.QSize(40, 40))
self.dateBtn.setObjectName("dateBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1006, 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)
self.infoBtn.clicked.connect(partial(self.show_popup))
self.dateBtn.clicked.connect(self.openDateWindow)
self.startBtn.clicked.connect(self.openDriveWindow)
self.contactsBtn.clicked.connect(self.openContactWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.infoBtn.setText(_translate("MainWindow", "About"))
self.startBtn.setText(_translate("MainWindow", "Driving Mode"))
def show_popup(self):
msg = QMessageBox()
msg.setWindowTitle('About Us')
msg.setText('Testing')
msg.setIcon(QMessageBox.Information)
x = msg.exec_()
def openDateWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_DateWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
def openDriveWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_DriveWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
def openContactWindow(self, MainWindow):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_ContactWindow()
self.ui.setupUi(self.window, MainWindow)
self.window.show()
MainWindow.hide()
app = QApplication(sys.argv)
splash = SplashScreen()
#splash.show()
sys.exit(app.exec_())
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_())
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 PyQt5 window (Windows OS) which recognizes a button click with holding CTRL button. I successfully created a handler which recognizes CTRL key press but it couldn't find the pressing and releasing of a button which i need to call and dismiss button click event. I did a lot of search but the resources for PyQt5 seems pretty low. Any help is appreciated :)
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setupUi(self)
self.show()
self.signals()
self.bleahOK=True
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(392, 255)
self.unlockButton = QtWidgets.QPushButton(Dialog)
self.unlockButton.setGeometry(QtCore.QRect(10, 180, 171, 51))
self.unlockButton.setObjectName("unlockButton")
self.lockButton = QtWidgets.QPushButton(Dialog)
self.lockButton.setGeometry(QtCore.QRect(220, 180, 151, 51))
self.lockButton.setObjectName("lockButton")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(30, 30, 331, 71))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(30, 120, 261, 31))
font = QtGui.QFont()
font.setPointSize(18)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.unlockButton.setText(_translate("Dialog", "OK"))
self.lockButton.setText(_translate("Dialog", "Lock"))
self.label.setText(_translate("Dialog", ""))
self.lineEdit.setText(_translate("Dialog", ""))
def signals(self):
self.unlockButton.clicked.connect(self.unlock)
def unlock(self):
if 1: print('ff')
def keyPressEvent(self, event):
if type(event) == QtGui.QKeyEvent: #Unable to find when the key was released
print (event.key())
event.accept()
else:
event.ignore()
def lock(self):
print("Test")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
# ui.signals()
# Dialog.show()
sys.exit(app.exec_())
I recommend you not to modify the code generated by Qt Designer, instead create a class that inherits the appropriate widget and use that class as an interface as I recommend PyQt. Going to the problem, you have to use the keyReleaseEvent method to listen when a key is released:
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(392, 255)
self.unlockButton = QtWidgets.QPushButton(Dialog)
self.unlockButton.setGeometry(QtCore.QRect(10, 180, 171, 51))
self.unlockButton.setObjectName("unlockButton")
self.lockButton = QtWidgets.QPushButton(Dialog)
self.lockButton.setGeometry(QtCore.QRect(220, 180, 151, 51))
self.lockButton.setObjectName("lockButton")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(30, 30, 331, 71))
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(Dialog)
self.lineEdit.setGeometry(QtCore.QRect(30, 120, 261, 31))
font = QtGui.QFont()
font.setPointSize(18)
self.lineEdit.setFont(font)
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.unlockButton.setText(_translate("Dialog", "OK"))
self.lockButton.setText(_translate("Dialog", "Lock"))
self.label.setText(_translate("Dialog", ""))
self.lineEdit.setText(_translate("Dialog", ""))
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.is_key_ctrl_pressed = False
self.unlockButton.clicked.connect(self.unlock)
#QtCore.pyqtSlot()
def unlock(self):
if self.is_key_ctrl_pressed:
print("unlock")
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Control:
self.is_key_ctrl_pressed = True
super(Dialog, self).keyPressEvent(event)
def keyReleaseEvent(self, event):
if event.key() == QtCore.Qt.Key_Control:
self.is_key_ctrl_pressed = False
super(Dialog, self).keyReleaseEvent(event)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
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.