(Python 3.7.3, PyQt5m MacOS Mojave)
In the code that follows I was hoping to see
start_batch
item
item
item
item
returned from start_batch
but what I actually get is
start_batch
returned from start_batch
That is, simulated_item is never running, not even once.
What do I need to do to correct this?
from PyQt5.QtCore import QTimer, QCoreApplication, QThread
import time, sys
class Scanner(object):
def __init__(self):
self.num = -1
def start_batch(self, operator_id, update_callback):
print('start_batch')
self.update_callback = update_callback
QTimer.singleShot(1, self.simulated_item)
def simulated_item(self):
print('item')
self.update_callback()
self.num += 1
if self.num > 4:
self.normal_stop_callback()
return
QTimer.singleShot(100, self.simulated_item)
class dummy(QThread):
def update(self):
print('update')
def run(self):
scnr = Scanner()
scnr.start_batch('opid', self.update)
print('returned from start_batch')
for i in range(10):
time.sleep((0.2))
app = QCoreApplication([])
thread = dummy()
thread.run()
In your code you have the error that you are calling the run method directly but that is not appropriate but you have to use the start() method:
app = QCoreApplication([])
thread = dummy()
thread.start()
app.exec_()
But you still won't get what you want.
Many elements such as the case of QTimer (also the signals) need an event loop to be able to work but when you override the run method that has it by default you have eliminated it so it fails.
So an approximation of what you want may be the following code where the QTimer uses the QCoreApplication event loop:
from PyQt5.QtCore import QTimer, QCoreApplication, QThread
import time, sys
class Scanner(object):
def __init__(self):
self.num = -1
def start_batch(self, operator_id, update_callback):
print("start_batch")
self.update_callback = update_callback
QTimer.singleShot(1, self.simulated_item)
def simulated_item(self):
print("item")
# QTimer.singleShot() is used so that the update_callback function
# is executed in the thread where the QObject to which it belongs lives,
# if it is not a QObject it will be executed in the thread
# where it is invoked
QTimer.singleShot(0, self.update_callback)
# self.update_callback()
self.num += 1
if self.num > 4:
# self.normal_stop_callback()
return
QTimer.singleShot(100, self.simulated_item)
class dummy(QThread):
def update(self):
print("update")
def run(self):
for i in range(10):
time.sleep(0.2)
print("returned from start_batch")
if __name__ == "__main__":
app = QCoreApplication(sys.argv)
thread = dummy()
thread.start()
scnr = Scanner()
thread.started.connect(lambda: scnr.start_batch("opid", thread.update))
sys.exit(app.exec_())
As discussed in the comment to #eyllansec above, I was able to create a working example which is shown below.
from PyQt5.QtCore import QTimer, QCoreApplication
import sys
class Scanner(object):
def __init__(self, app):
self.num = -1
self.app = app
def simulated_item(self):
self.num += 1
print("item", self.num)
if self.num <= 4:
QTimer.singleShot(500, self.simulated_item)
else:
self.app.exit()
if __name__ == "__main__":
app = QCoreApplication(sys.argv)
scnr = Scanner(app)
scnr.simulated_item()
sys.exit(app.exec_())
Related
My main objective is to show a constantly evolving value on a Qt-window textEdit. (this window contains only a checkBox and a textEdit).
Sadly, I cannot click on the checkbox and the window is frozen until I shutdown the terminal.
import sys
from threading import Thread
from random import randint
import time
from PyQt4 import QtGui,uic
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
#function to continually change the targeted value
def run(self):
for i in range(1, 20):
self.a = randint (1, 10)
secondsToSleep = 1
time.sleep(secondsToSleep)
class MyWindow(QtGui.QMainWindow,Thread):
def __init__(self):
Thread.__init__(self)
super(MyWindow,self).__init__()
uic.loadUi('mywindow.ui',self)
self.checkBox.stateChanged.connect(self.checkeven)
self.show()
#i show the value only if the checkbox is checked
def checkeven(self):
while self.checkBox.isChecked():
self.textEdit.setText(str(myThreadOb1.a))
# Run following code when the program starts
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
# Declare objects of MyThread class
myThreadOb1 = MyThread()
myThreadOb2 = MyWindow()
# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()
sys.exit(app.exec_())
At the moment I'm using a thread to set a random value to a, but at the end it is supposed to be a bit more complex as I will have to take the values from an automation.
Do you have any clue why my code is acting like this?
Thank you very much for your help.
The problem is that the while self.checkBox.isChecked() is blocking, preventing the GUI from handling other events.
Also you should not run a PyQt GUI on another thread than the main one.
If you want to send data from one thread to another, a good option is to use the signals.
Doing all these considerations we have the following:
import sys
from threading import Thread
from random import randint
import time
from PyQt4 import QtGui, uic, QtCore
class MyThread(Thread, QtCore.QObject):
aChanged = QtCore.pyqtSignal(int)
def __init__(self):
Thread.__init__(self)
QtCore.QObject.__init__(self)
#function to continually change the targeted value
def run(self):
for i in range(1, 20):
self.aChanged.emit(randint(1, 10))
secondsToSleep = 1
time.sleep(secondsToSleep)
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow,self).__init__()
uic.loadUi('mywindow.ui',self)
self.thread = MyThread()
self.thread.aChanged.connect(self.on_a_changed, QtCore.Qt.QueuedConnection)
self.thread.start()
self.show()
#i show the value only if the checkbox is checked
#QtCore.pyqtSlot(int)
def on_a_changed(self, a):
if self.checkBox.isChecked():
self.textEdit.setText(str(a))
# Run following code when the program starts
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
# Declare objects of MyThread class
w = MyWindow()
sys.exit(app.exec_())
An option more to the style of Qt would be to use QThread since it is a class that handles a thread and is a QObject so it handles the signals easily.
import sys
from random import randint
from PyQt4 import QtGui, uic, QtCore
class MyThread(QtCore.QThread):
aChanged = QtCore.pyqtSignal(int)
def run(self):
for i in range(1, 20):
self.aChanged.emit(randint(1, 10))
secondsToSleep = 1
QtCore.QThread.sleep(secondsToSleep)
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow,self).__init__()
uic.loadUi('mywindow.ui',self)
self.thread = MyThread()
self.thread.aChanged.connect(self.on_a_changed, QtCore.Qt.QueuedConnection)
self.thread.start()
self.show()
#i show the value only if the checkbox is checked
#QtCore.pyqtSlot(int)
def on_a_changed(self, a):
if self.checkBox.isChecked():
self.textEdit.setText(str(a))
# Run following code when the program starts
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
# Declare objects of MyThread class
w = MyWindow()
sys.exit(app.exec_())
I would like use a Qmessagebox in order to display some info about a running computation and as a stop function when I click on the OK button.
However when I use the signal buttonClicked nothing is happenning and hte function connect with it is never called
Here a code to illustrate my issue:
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class SenderObject(QObject):
something_happened = pyqtSignal( )
class myfunc():
updateTime = SenderObject()
def __init__(self):
self.i = 0
self.stop = True
def run(self):
while self.stop :
self.i+=1
if self.i%100 == 0:
self.updateTime.something_happened.emit()
print('infinit loop',self.i)
class SurfViewer(QMainWindow):
def __init__(self, parent=None):
super(SurfViewer, self).__init__()
self.parent = parent
self.setFixedWidth(200)
self.setFixedHeight(200)
self.wid = QWidget()
self.setCentralWidget(self.wid)
self.groups = QHBoxLayout() ####
self.Run = QPushButton('Run')
self.groups.addWidget(self.Run)
self.wid.setLayout(self.groups)
self.Run.clicked.connect(self.run)
self.myfunc = myfunc()
self.myfunc.updateTime.something_happened.connect(self.updateTime)
def run(self):
self.msg = QMessageBox()
self.msg.setText('Click Ok to stop the loop')
self.msg.setWindowTitle(" ")
self.msg.setModal(False)
self.msg.show()
self.myfunc.run()
self.msg.buttonClicked.connect(self.Okpressed)
def Okpressed(self):
self.myfunc.stop = False
#pyqtSlot( )
def updateTime(self ):
self.msg.setText('Click Ok to stop the loop\ni = '+str(self.myfunc.i))
self.parent.processEvents()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SurfViewer(app)
ex.setWindowTitle('window')
ex.show()
sys.exit(app.exec_( ))
So theself.msg.buttonClicked.connect(self.Okpressed) line never call the function Okpressed. Therefore, myfunc.run is never stopped.
Somebody could help on this?
write
self.msg.buttonClicked.connect(self.Okpressed)
before
self.myfunc.run()
If you call run function before subscribing click event, curse will stuck into infinite while loop. so your click event never subscribed.
First subscribe click event and then call "run" function of "myfunc"
And yes never do this -
from PyQt4.QtGui import *
from PyQt4.QtCore import *
Its vbad programming practice. You can write like
from PyQt4 import QtGui
And use into code like
QtGui.QMessagebox
I am trying to load some data which takes 30+ seconds. During this time I wish the user to see a small GUI which says "Loading .", then "Loading ..", then "Loading ...", then "Loading ." etc. I have done some reading and I think I have to put this in a separate thread. I found someone who had a similar problem suggesting the solution was this in the right spot:
t = threading.Thread(target=self.test)
t.daemon = True
t.start()
In a lower part of the file I have the test function
def test(self):
tmp = InfoMessage()
while True:
print(1)
and the InfoMessage function
from PyQt5 import uic, QtCore, QtGui, QtWidgets
import sys
class InfoMessage(QtWidgets.QDialog):
def __init__(self, msg='Loading ', parent=None):
try:
super(InfoMessage, self).__init__(parent)
uic.loadUi('ui files/InfoMessage.ui',self)
self.setWindowTitle(' ')
self.o_msg = msg
self.msg = msg
self.info_label.setText(msg)
self.val = 0
self.timer = QtCore.QTimer()
self.timer.setInterval(500)
self.timer.timeout.connect(self.update_message)
self.timer.start()
self.show()
except BaseException as e:
print(str(e))
def update_message(self):
self.val += 1
self.msg += '.'
if self.val < 20:
self.info_label.setText(self.msg)
else:
self.val = 0
self.msg = self.o_msg
QtWidgets.QApplication.processEvents()
def main():
app = QtWidgets.QApplication(sys.argv) # A new instance of QApplication
form = InfoMessage('Loading ') # We set the form to be our MainWindow (design)
app.exec_() # and execute the app
if __name__ == '__main__': # if we're running file directly and not importing it
main() # run the main function
When I run the InfoMessage function alone it works fine and it updates every 0.5 seconds etc. However, when I fun this as part of the loading file the GUI is blank and incorrectly displayed. I know it is staying in the test function because of the print statement in there.
Can someone point me in the right direction? I think I am missing a couple of steps.
First, there are two ways of doing this. One way is to use the Python builtin threading module. The other way is to use the QThread library which is much more integrated with PyQT. Normally, I would recommend using QThread to do threading in PyQt. But QThread is only needed when there is any interaction with PyQt.
Second, I've removed processEvents() from InfoMessage because it does not serve any purpose in your particular case.
Finally, setting your thread as daemon implies your thread will never stop. This is not the case for most functions.
import sys
import threading
import time
from PyQt5 import uic, QtCore, QtWidgets
from PyQt5.QtCore import QThread
def long_task(limit=None, callback=None):
"""
Any long running task that does not interact with the GUI.
For instance, external libraries, opening files etc..
"""
for i in range(limit):
time.sleep(1)
print(i)
if callback is not None:
callback.loading_stop()
class LongRunning(QThread):
"""
This class is not required if you're using the builtin
version of threading.
"""
def __init__(self, limit):
super().__init__()
self.limit = limit
def run(self):
"""This overrides a default run function."""
long_task(self.limit)
class InfoMessage(QtWidgets.QDialog):
def __init__(self, msg='Loading ', parent=None):
super(InfoMessage, self).__init__(parent)
uic.loadUi('loading.ui', self)
# Initialize Values
self.o_msg = msg
self.msg = msg
self.val = 0
self.info_label.setText(msg)
self.show()
self.timer = QtCore.QTimer()
self.timer.setInterval(500)
self.timer.timeout.connect(self.update_message)
self.timer.start()
def update_message(self):
self.val += 1
self.msg += '.'
if self.val < 20:
self.info_label.setText(self.msg)
else:
self.val = 0
self.msg = self.o_msg
def loading_stop(self):
self.timer.stop()
self.info_label.setText("Done")
class MainDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
# QThread Version - Safe to use
self.my_thread = LongRunning(limit=10)
self.my_thread.start()
self.my_loader = InfoMessage('Loading ')
self.my_thread.finished.connect(self.my_loader.loading_stop)
# Builtin Threading - Blocking - Do not use
# self.my_thread = threading.Thread(
# target=long_task,
# kwargs={'limit': 10}
# )
# self.my_thread.start()
# self.my_loader = InfoMessage('Loading ')
# self.my_thread.join() # Code blocks here
# self.my_loader.loading_stop()
# Builtin Threading - Callback - Use with caution
# self.my_loader = InfoMessage('Loading ')
# self.my_thread = threading.Thread(
# target=long_task,
# kwargs={'limit': 10,
# 'callback': self.my_loader}
# )
# self.my_thread.start()
def main():
app = QtWidgets.QApplication(sys.argv)
dialog = MainDialog()
app.exec_()
if __name__ == '__main__':
main()
Feel free to ask any follow up questions regarding this code.
Good Luck.
Edit:
Updated to show how to run code on thread completion. Notice the new parameter added to long_task function.
import time
import sys, threading
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication
class Global:
def __init__(self):
for c in MyClass, MainWindow:
cl = c()
setattr(self, c.__name__, cl)
setattr(cl, 'global_', self)
class MyClass:
def work(self):
for r in range(100):
if r == 2:
self.global_.MainWindow.SignalBox.emit('MyClass NO PAUSE') # need pause !!!
else:
print(r)
time.sleep(1)
class MainWindow(QtGui.QWidget):
Signal = QtCore.pyqtSignal(str)
SignalBox = QtCore.pyqtSignal(str)
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(300, 300)
self.lab = QtGui.QLabel()
lay = QtGui.QGridLayout()
lay.addWidget(self.lab)
self.setLayout(lay)
self.msgBox = lambda txt: getattr(QtGui.QMessageBox(), 'information')(self, txt, txt)
self.Signal.connect(self.lab.setText)
self.SignalBox.connect(self.msgBox)
def thread_no_wait(self):
self.global_.MainWindow.SignalBox.emit('MyClass PAUSE OK')
threading.Thread(target=self.global_.MyClass.work).start()
def thread_main(self):
def my_work():
for r in range(100):
self.Signal.emit(str(r))
time.sleep(1)
threading.Thread(target=my_work).start()
if __name__ == '__main__':
app = QApplication(sys.argv)
g = Global()
g.MainWindow.show()
g.MainWindow.thread_main()
g.MainWindow.thread_no_wait()
app.exec_()
how to run a QMessageBox from another process?
MyClass.work performed in a separate thread without join is necessary to MyClass suspended if it causes QMessageBox If we define QMessageBox is the MainWindow , the error will be called
QObject :: startTimer: timers can not be started from another thread
QApplication: Object event filter can not be in a different thread.
And in this call QMessageBox invoked in a separate thread , and the work is not suspended
It sounds like you want to pause execution of a thread until certain operations in the main thread complete. There are a few ways you can do this. A simple way is to use a shared global variable.
PAUSE = False
class MyClass:
def work(self):
global PAUSE
for r in range(100):
while PAUSE:
time.sleep(1)
if r == 2:
self.global_.MainWindow.SignalBox.emit('MyClass NO PAUSE')
PAUSE = True
...
class MainWindow(...)
def msgBox(self, txt):
QtGui.QMessageBox.information(self, txt, txt)
global PAUSE
PAUSE = False
If you use QThreads instead of python threads, you can actually call functions in another thread and block until that function completes using QMetaObject.invokeMethod
#QtCore.pyqtSlot(str)
def msgBox(self, txt):
...
...
if r == 2:
# This call will block until msgBox() returns
QMetaObject.invokeMethod(
self.global_.MainWindow,
'msgBox',
QtCore.Qt.BlockingQueuedConnection,
QtCore.Q_ARG(str, 'Text to msgBox')
)
I am having some trouble applying the new pyqt5 signals and slots into a script thats purpose is to test/invoke another problem I've been trying to solve, GUI freezing/crashing ... the aim is so that once these signals and slots are functioning correctly the GUI will not crash after +/- 30 seconds of runtime, and just continue on counting numbers until the end of time. I have provided a pyqt4 example although it would be great to have a pyqt5 solution. Thanks :)
from time import sleep
import os
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
import random
import os
import time
class Cr(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
while True:
rndInt = random.randint(1, 100000)
timesleep = random.random()
time.sleep(timesleep)
for i in range(120):
self.emit(QtCore.SIGNAL('host_UP'), 'foo' + str(rndInt), i)
QtGui.QApplication.processEvents()
class Main_Window(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
self.relativePath = os.path.dirname(sys.argv[0])
self.Main_Window = uic.loadUi("Main_Window.ui", self)
self.Main_Window.show()
self.Main_Window.move(790, 300)
self.GU = []
ProgressThreads = self.printThreads
self.details_label = []
for i in range(120):
self.details_label.insert(i, 0)
self.details_label[i] = QLabel(" ")
ProgressThreads.addWidget(self.details_label[i])
ProgressThreads.addSpacing(6)
self.details_label[i].setText(Tools.Trim.Short('Idle', 7))
self.GU.insert(i, Cr())
self.GU[i].start()
self.connect(self.GU, QtCore.SIGNAL("host_UP"), self.UpdateHost)
def UpdateHost(self, str1, pos1):
self.details_label[pos1].setText(str1)
class guiUpdate():
def GUI_main(self):
self.GUI = GUI
if __name__ == "__main__":
app = QApplication(sys.argv)
guiUpdate.GUI_main.GUI = Main_Window()
sys.exit(app.exec_())
Thank you for the help :)
UPDATE
The script below is a hopefully correct PyQt5 version of the script above. However the issue of crashing and 'not responding' message is still unresolved
from time import sleep
import os
from PyQt5 import QtCore, QtGui, uic
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QObject, pyqtSignal
import random
import os
import time
import Tools
import sys
class Cr(QtCore.QThread):
def __init__(self, sam):
QtCore.QThread.__init__(self)
self.sam = sam
def run(self):
while True:
rndInt = random.randint(1, 100000)
timesleep = random.random()
time.sleep(timesleep)
for i in range(5):
#time.sleep(1)
self.sam.connect_and_emit_trigger('foo' + str(rndInt), i)
#self.emit(QtCore.SIGNAL('host_UP'), 'foo' + str(rndInt), i)
#QtGui.QApplication.processEvents()
class Main_Window(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
self.relativePath = os.path.dirname(sys.argv[0])
self.Main_Window = uic.loadUi("Main_Window.ui", self)
self.Main_Window.show()
self.Main_Window.move(790, 300)
sam = Foo()
self.GU = []
ProgressThreads = self.ProgressThreads
self.details_label = []
for i in range(5):
self.details_label.insert(i, 0)
self.details_label[i] = QLabel(" ")
ProgressThreads.addWidget(self.details_label[i])
ProgressThreads.addSpacing(6)
self.details_label[i].setText(Tools.Trim.Short('Idle', 7))
self.GU.insert(i, Cr(sam))
self.GU[i].start()
class Foo(QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = pyqtSignal()
def connect_and_emit_trigger(self, str, i):
self.str = str
self.i = i
self.trigger.connect(self.handle_trigger)
self.trigger.emit()
def handle_trigger(self):
guiUpdate.GUI_main.GUI.details_label[self.i].setText(self.str)
class guiUpdate():
def GUI_main(self):
self.GUI = GUI
if __name__ == "__main__":
app = QApplication(sys.argv)
guiUpdate.GUI_main.GUI = Main_Window()
sys.exit(app.exec_())
The new recommended way to use threads (and the one I got the best results with) is to use moveToThread() instead of directly subclassing QThread. In short:
write a QObject subclass doing the actual work (let's call it QMyWorker). This will likely look a bit like your existing qthread subclass, with a start() or run() method etc.
create a parent-less instance of QMyWorker
create a parent-less instance of QThread
use QMyWorker.moveToThread(your_thread_instance) (I go by memory, double check the API in doc).
call your QMyWorker.start()
This approach worked for me for very long jobs (4GB files etc).
I used QThreadPool, QRunnable with a worker, can make more workers per thread.
Very good example with explanation here
https://martinfitzpatrick.name/article/multithreading-pyqt-applications-with-qthreadpool/
My PYQT5 was freezing up also, now i fine tune it with printing a TimeStamp