I'm trying to make basic functionality
after pressing "start" button start counter , after pressing stop button stop counter,
but after I start process, it looks like only counting thread is working and it's not possible to press stop button
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
from test.test_sax import start
import time
from threading import Thread
import threading
class Example(QtGui.QWidget):
x = 1
bol = True
def __init__(self):
super(Example, self).__init__()
self.qbtn = QtGui.QPushButton('Quit', self)
self.qbtn.resize(self.qbtn.sizeHint())
self.qbtn.move(50, 50)
self.qbtn2 = QtGui.QPushButton('Start', self)
self.qbtn2.resize(self.qbtn2.sizeHint())
self.qbtn2.move(150, 50)
self.qbtn.clicked.connect(self.stopCounter)
self.qbtn2.clicked.connect(self.startUI)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Quit button')
self.show()
def stopCounter(self):
Example.bol = False
def startUI(self):
Example.bol = True
thread = Thread(self.counterr())
def counterr(self):
x = 0
while Example.bol:
print x
x += 1
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
a = Example()
sys.exit(app.exec_())
thx
Now you call the slow function before you even create the thread. Try this instead:
thread = Thread(target=self.counterr)
thread.start()
In a Qt application you might also consider the QThread class that can run its own event loop and communicate with your main thread using signals and slots.
You are using the Thread class completely incorrectly, I'm afraid. You are passing it the result of the counterr method, which never returns.
Pass counterr (without calling it) to the Thread class as the target, then start it explicitly:
def startUI(self):
self.bol = True
thread = Thread(target=self.counterr)
thread.start()
Also, just access bol as an instance variable, not a class variable.
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
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
I have a problem with PyQT4 for Python. There is a label with text and button connected to function. The function could change the text of label first, then call other function. There is a problem with it: the function is executed firts, then change text of the label.
Code:
# -*- coding: utf-8 -*-
import time
import sys
from PyQt4 import QtCore, QtGui
def timesleep():
print("start sleep")
time.sleep(5)
print("stop sleep")
class AnyWidget(QtGui.QWidget):
def __init__(self,*args):
QtGui.QWidget.__init__(self,*args)
self.setWindowTitle("PETHARD")
boxlay = QtGui.QHBoxLayout(self)
frame = QtGui.QFrame(self) # Фрейм
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
gridlay = QtGui.QGridLayout(frame) # Менеджер размещения элементов во фрейме
label = QtGui.QLabel(u"Welcome",frame) # Текстовая метка.
global glabel
glabel = label
gridlay.addWidget(label,0,0)
button1 = QtGui.QPushButton(u"Load From MC", frame)
self.connect(button1, QtCore.SIGNAL("clicked()"), self.ts)
gridlay.addWidget(button1,1,0)
boxlay.addWidget(frame)
def ts(self):
global glabel
glabel.setText(u"Waiting...")
timesleep()
if __name__=="__main__":
app = QtGui.QApplication(sys.argv)
aw = AnyWidget()
aw.show()
sys.exit(app.exec_())
Help me please to fix this problem.
It work's like that because rendering is done later in app. So your glabel.text is changed immediately but you will see changed text on screen after your ts function call, because drawing is done at the end of loop.
If you really want to call your function in new frame (after rendering of new text) then use timer:
timer = QtCore.QTimer()
QtCore.QObject.connect(
timer,
QtCore.SIGNAL("timeout()"),
self.ts
)
timer.start(10)
It should call your function ten milisecond later, so in fact probably after rendering.
You never want to tie-up your GUI with a long-running function. That the label does not update is only one manifestation of the problem. Even if you get the label to update before the function is called, it will still "freeze" your GUI -- no widget will respond to the user until the long-running function completes.
If you have to run such a function, see if there is a way to break it up into small pieces which each relinquish control to the GUI, or consider using a separate thread to run the function:
import time
import sys
from PyQt4 import QtCore, QtGui
class TimeSleep(QtCore.QThread):
def __init__(self, parent=None):
QtCore.QThread.__init__(self, parent)
self.parent = parent
def run(self):
print("start sleep")
time.sleep(5)
print("stop sleep")
self.parent.glabel.setText(u"Done")
class AnyWidget(QtGui.QWidget):
def __init__(self, *args):
QtGui.QWidget.__init__(self, *args)
self.setWindowTitle("PETHARD")
boxlay = QtGui.QHBoxLayout(self)
frame = QtGui.QFrame(self) # Фрейм
frame.setFrameShape(QtGui.QFrame.StyledPanel)
frame.setFrameShadow(QtGui.QFrame.Raised)
gridlay = QtGui.QGridLayout(
frame) # Менеджер размещения элементов во фрейме
label = QtGui.QLabel(u"Welcome", frame) # Текстовая метка.
self.glabel = label
gridlay.addWidget(label, 0, 0)
button1 = QtGui.QPushButton(u"Load From MC", frame)
self.connect(button1, QtCore.SIGNAL("clicked()"), self.ts)
gridlay.addWidget(button1, 1, 0)
boxlay.addWidget(frame)
def ts(self):
self.glabel.setText(u"Waiting...")
self.thread = TimeSleep(parent=self)
self.thread.start()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
aw = AnyWidget()
aw.show()
sys.exit(app.exec_())
Here is a wiki page on how to deal with long-running functions.
The text of the label is being changed, but because you're blocking the main thread you're not giving Qt a chance to paint it.
Use QCoreApplication::processEvents and QCoreApplication::flush:
def ts(self):
glabel.setText(u"Waiting...")
QtCore.QCoreApplication.processEvents()
QtCore.QCoreApplication.flush()
timesleep()