PyQt Threading: GUI interaction Crashes Program - python

I am designing a program to edit DICOMs. Specifically, I am having issues appropriately interacting with my PyQt UI.
I want to be able to click on a "pause" and on a "stop" button to either pause or stop my editing function. My editing function takes a significant amount of time to process / loop through. Depending on the number of files that it is editing, it can take anywhere from 30 seconds to over an hour. Because of this, I decided to throw my editing function into its own thread using the native threading capabilities of Qt. I was able to get the thread working ie: from my MainWindow class I can click a button that initializes my editing class (class edit(QThread), however interacting with the GUI still crashes the program and I'm not sure why! Below I have added a sample of the general code structure / set up that I am using.
class anonymizeThread(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
#def sendAnon(self, progress_val):
# self.completed = 0
# return self.completed
def run(self):
# while self.completed < 100:
# self.completed += 0.00001
# self.emit(QtCore.SIGNAL('PROGRESS'), self.completed)
# ANONYMIZE FUNCTION!
i = 0
#flag = self.stop_flag
while i < 10000000: # and self.stop_flag is not 1:
print(i)
i+=1
print('i didnt enter the loop')
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
# connect the buttons
self.worker = anonymizeThread()
self.anonbtn.clicked.connect(self.anonymize)
self.open_directory.clicked.connect(self.open_dir)
self.pause.clicked.connect(self.paused)
self.stopbtn.clicked.connect(self.stopped)
# block button signals to start
self.pause.blockSignals(True)
self.stopbtn.blockSignals(True)
self.dir_name = None
self.pause_flag = None
self.stop_flag = None
self.anon_flag = None
# This is how we quit from the main menu "File" option
extractAction = self.actionQuit_Ctrl_Q
extractAction.setShortcut("Ctrl+Q")
extractAction.setStatusTip('Leave The App')
extractAction.triggered.connect(self.close_application)
def updateProgressBar(self,val):
self.progressBar.setValue(val)
def close_application(self):
choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
sys.exit()
else:
pass
def anonymize(self):
self.pause.blockSignals(False)
self.stopbtn.blockSignals(False)
self.worker.start()
# check if directory chosen
# self.progressBar.setMaximum(len(dcm)
# start our anon thread!
def paused(self):
#only if running
if self.pause_flag is 0:
self.pause_flag = 1
self.pause.setText('Start')
elif self.pause_flag is 1:
self.pause_flag = 0
self.pause.setText('Pause')
else:
pass
def stopped(self): # need a self.stop() for anonThread
choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
self.stop_flag = 1
#self.stopbtn.blockSignals(True)
#self.paused.blockSignals(True)
else:
pass
def open_dir(self):
self.dir_name = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
if len(self.dir_name) is not 0:
self.anon_flag = 0
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

It is advisable not to access the flags directly, it is better to do it through the functions to make use of it transparently, for this the same class should verify the tasks.
Also it is good to give a small delay so that the application can deal with the graphic part, another possible improvement is to avoid usat sys.exit, you could call the close method that closes the window.
In the following code I have implemented the stop and pause methods.
class anonymizeThread(QThread):
def __init__(self):
QThread.__init__(self)
self.onRunning = True
self.onStop = False
def __del__(self):
self.wait()
def stop(self):
self.onStop = True
def pause(self):
if self.isRunning():
self.onRunning = not self.onRunning
def run(self):
i = 0
#flag = self.stop_flag
while i < 10000000:
if self.onRunning: # and self.stop_flag is not 1:
print(i)
i+=1
if self.onStop:
break
QThread.msleep(10)
print('i didnt enter the loop')
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
# connect the buttons
self.worker = anonymizeThread()
self.anonbtn.clicked.connect(self.anonymize)
self.pause.clicked.connect(self.paused)
self.stopbtn.clicked.connect(self.stopped)
# block button signals to start
self.pause.blockSignals(True)
self.stopbtn.blockSignals(True)
def close_application(self):
choice = QMessageBox.question(self, 'Just had to check...', "Are you sure you want to exit?", QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
self.close()
def anonymize(self):
self.pause.blockSignals(False)
self.stopbtn.blockSignals(False)
self.worker.start()
def paused(self):
self.worker.pause()
def stopped(self): # need a self.stop() for anonThread
choice = QMessageBox.question(self,'Stop', "Are you sure you want to stop? You will not be able to pick up exactly where you left off.",
QMessageBox.Yes | QMessageBox.No)
if choice == QMessageBox.Yes:
self.worker.stop()

Thanks to #eyllansec and #ekhumoro..
In the above code, all instances of self.stop_flag = ... should have been self.worker.stop_flag = ... as it is changing the variable that is to be used in the worker class/thread. My mistake was assuming both classes inherited the same "self".
If there are other errors and or better explanations of what I did incorrectly, please do post an answer and I'll accept it!

Related

Call method to the main thread 'from a sub thread'

I am making a data acquisition program that communicates with a measurement device. The status of the device needs to be checked periodically (e.g., every 0.1 sec) to see if acquisition is done. Furthermore, the program must have the 'abort' method because acquisition sometime takes longer than few minutes. Thus I need to use multi-threading.
I attached the flow-chart and the example code. But I have no idea how I call the main-thread to execute a method from the sub-thread.
python 3.7.2
wxpython 4.0.6
Flow Chart
import wx
import time
from threading import Thread
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Test Frame")
panel = wx.Panel(self)
self.Btn1 = wx.Button(panel, label="Start Measurement")
self.Btn1.Bind(wx.EVT_BUTTON, self.OnStart)
self.Btn2 = wx.Button(panel, label="Abort Measurement")
self.Btn2.Bind(wx.EVT_BUTTON, self.OnAbort)
self.Btn2.Enable(False)
self.DoneFlag = False
self.SubThread = Thread(target=self.Check, daemon=True)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.Btn1, 0, wx.EXPAND)
sizer.Add(self.Btn2, 0, wx.EXPAND)
panel.SetSizer(sizer)
def OnStart(self, event):
# self.N is the number of data points
self.N = 0
# self.N_max is the number of data points that is going to be acquired
self.N_max = int(input("How many data points do yo want? (greater than 1) : "))
self.DoneFlag = False
self.Btn1.Enable(False)
self.Btn2.Enable(True)
self.Start()
def OnAbort(self, event):
self.DoneFlag = True
def Start(self):
self.SubThread.start()
def Done(self):
if self.DoneFlag is True:
self.Finish()
elif self.DoneFlag is False:
self.Start()
def Finish(self):
print("Measurement done (N = {})\n".format(self.N))
self.Btn1.Enable(True)
self.Btn2.Enable(False)
def Check(self):
# In the actual program, this method communicates with a data acquisition device to check its status
# For example,
# "RunningStatus" is True when the device is still running (acquisition has not been done yet),
# is False when the device is in idle state (acquisition has done)
#
# [Structure of the actual program]
# while True:
# RunningStatus = GetStatusFromDevice()
# if RunningStatus is False or self.DoneFlag is True:
# break
# else:
# time.sleep(0.1)
# In below code, it just waits 3 seconds then assumes the acqusition is done
t = time.time()
time.sleep(1)
for i in range(3):
if self.DoneFlag is True:
break
print("{} sec left".format(int(5-time.time()+t)))
time.sleep(1)
# Proceed to the next steps after the acquisition is done.
if self.DoneFlag is False:
self.N += 1
print("Data acquired (N = {})\n".format(self.N))
if self.N == self.N_max:
self.DoneFlag = True
self.Done() # This method should be excuted in the main thread
if __name__ == "__main__":
app = wx.App()
frame = TestFrame()
frame.Show()
app.MainLoop()
When using a GUI it is not recommended to call GUI functions from another thread, see:
https://docs.wxwidgets.org/trunk/overview_thread.html
One of your options, is to use events to keep track of what is going on.
One function creates and dispatches an event when something happens or to denote progress for example, whilst another function listens for and reacts to a specific event.
So, just like pubsub but native.
Here, I use one event to post information about progress and another for results but with different targets.
It certainly will not be an exact fit for your scenario but should give enough information to craft a solution of your own.
import time
import wx
from threading import Thread
import wx.lib.newevent
progress_event, EVT_PROGRESS_EVENT = wx.lib.newevent.NewEvent()
results_event, EVT_RESULTS_EVENT = wx.lib.newevent.NewEvent()
class ThreadFrame(wx.Frame):
def __init__(self, title, parent=None):
wx.Frame.__init__(self, parent=parent, title=title)
panel = wx.Panel(self)
self.parent = parent
self.btn = wx.Button(panel,label='Stop Measurements', size=(200,30), pos=(10,10))
self.btn.Bind(wx.EVT_BUTTON, self.OnExit)
self.progress = wx.Gauge(panel,size=(240,10), pos=(10,50), range=30)
#Bind to the progress event issued by the thread
self.Bind(EVT_PROGRESS_EVENT, self.OnProgress)
#Bind to Exit on frame close
self.Bind(wx.EVT_CLOSE, self.OnExit)
self.Show()
self.mythread = TestThread(self)
def OnProgress(self, event):
self.progress.SetValue(event.count)
#or for indeterminate progress
#self.progress.Pulse()
if event.result != 0:
evt = results_event(result=event.result)
#Send back result to main frame
try:
wx.PostEvent(self.parent, evt)
except:
pass
def OnExit(self, event):
if self.mythread.isAlive():
self.mythread.terminate() # Shutdown the thread
self.mythread.join() # Wait for it to finish
self.Destroy()
class TestThread(Thread):
def __init__(self,parent_target):
Thread.__init__(self)
self.parent = parent_target
self.stopthread = False
self.start() # start the thread
def run(self):
curr_loop = 0
while self.stopthread == False:
curr_loop += 1
# Send a result every 3 seconds for test purposes
if curr_loop < 30:
time.sleep(0.1)
evt = progress_event(count=curr_loop,result=0)
#Send back current count for the progress bar
try:
wx.PostEvent(self.parent, evt)
except: # The parent frame has probably been destroyed
self.terminate()
else:
curr_loop = 0
evt = progress_event(count=curr_loop,result=time.time())
#Send back current count for the progress bar
try:
wx.PostEvent(self.parent, evt)
except: # The parent frame has probably been destroyed
self.terminate()
def terminate(self):
evt = progress_event(count=0,result="Measurements Ended")
try:
wx.PostEvent(self.parent, evt)
except:
pass
self.stopthread = True
class MyPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text_count = 0
self.thread_count = 0
self.parent=parent
btn = wx.Button(self, wx.ID_ANY, label='Start Measurements', size=(200,30), pos=(10,10))
btn.Bind(wx.EVT_BUTTON, self.Thread_Frame)
btn2 = wx.Button(self, wx.ID_ANY, label='Is the GUI still active?', size=(200,30), pos=(10,50))
btn2.Bind(wx.EVT_BUTTON, self.AddText)
self.txt = wx.TextCtrl(self, wx.ID_ANY, style= wx.TE_MULTILINE, pos=(10,90),size=(400,100))
#Bind to the result event issued by the thread
self.Bind(EVT_RESULTS_EVENT, self.OnResult)
def Thread_Frame(self, event):
self.thread_count += 1
frame = ThreadFrame(title='Measurement Task '+str(self.thread_count), parent=self)
def AddText(self,event):
self.text_count += 1
txt = "Gui is still active " + str(self.text_count)+"\n"
self.txt.write(txt)
def OnResult(self,event):
txt = "Result received " + str(event.result)+"\n"
self.txt.write(txt)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main Frame', size=(600,400))
panel = MyPanel(self)
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MainFrame()
app.MainLoop()

Why can't I call the function inside a certain class

I'm currently having a project that opens a Main Window and then opens the second window upon clicking a button. The Main window class is fine and is able to call the functions inside it while the second window can still show it's UI but can't call it's functions(button in the second window is not calling the function it's supposed to call). Is there something I missed?
class MainWindow():
def __init__(self, dlg):
self.dlg = dlg
dlg.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
dlg.systemBase.setText(make_prefix(Sbase)+"VA")
dlg.comboBox.currentTextChanged.connect(self.Calc)
dlg.comboBox.addItem(str(380.00/1e3))
dlg.comboBox.addItem(str(400.00/1e3))
dlg.comboBox.addItem(str(220.00/1e3))
dlg.lineEdit_3.setPlaceholderText("Accepts 1-10")
dlg.lineEdit_3.setValidator(QIntValidator(1,10))
dlg.lineEdit_3.textChanged.connect(self.disableButton)
dlg.comboBox_2.addItem("Single Phase")
dlg.comboBox_2.addItem("3 Phase")
dlg.pushButton_3.setDisabled(True)
dlg.pushButton_3.clicked.connect(self.selectPhase)
dlg.lineEdit_3.setFocus()
dlg.lineEdit_3.returnPressed.connect(self.selectPhase)
dlg.show()
app.exec()
def Calc(self):
Vbase=float(self.dlg.comboBox.currentText())
currentBase = ((Sbase)/ (math.sqrt(3) * (Vbase*1e3)))
dlg.currentBase.setText(str(make_prefix(currentBase))+"A")
baseImpedance = (((Vbase*1e3)*(Vbase*1e3)) / (Sbase))
dlg.baseImpedance.setText(str(make_prefix(baseImpedance))+" p.u.")
def selectPhase(self):
Nbus = dlg.lineEdit_3.text()
if Nbus == "1":
self.SW = uic.loadUi("try1.ui")
SecondWindow(self.SW) #calling the second window
else:
print("try again")
print(int(Nbus))
if self.dlg.comboBox_2.currentText() == "Single Phase":
print("u selected single phase")
else:
print("u selected 3 phase")
def disableButton(self):
if len(self.dlg.lineEdit_3.text()) > 0:
dlg.pushButton_3.setDisabled(False)
else:
dlg.pushButton_3.setDisabled(True)
class SecondWindow():
def __init__(self, SW):
self.SW = SW
#Button
SW.pushButton.setText("Calculate")
SW.pushButton.clicked.connect(self.tst) #nothing happens in clicking the button.
SW.show()
def tst(self):
print("testing")
if __name__ == '__main__':
app = QtWidgets.QApplication([])
dlg=uic.loadUi("try.ui")
MainWindow(dlg)
I expect to print the string inside the tst() function from SecondWindow class.

Python,Gtk3: How to make the Progress bar pulsing while other stuffs are running

Based on Classes, i have window which contain a button and progressbar, whenever the button is clicked there two things should happen :
1 - should entried value from dialog pass to class ABCD
2 - While our class ABCD() do his stuff, should our progressbar do regular pulsing untill the class ABCD() finish process.
So the problem is that the progressbar pulse only one time,then stucked there till the class ABCD() finished, then its start pulsing regulary later.
Here is my try:
import gi,time
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
class DialogExample(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OK, Gtk.ResponseType.OK))
self.set_default_size(150, 100)
self.Myinput = Gtk.Entry()
box = self.get_content_area()
box.add(self.Myinput)
self.show_all()
class DialogWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Dialog Example")
self.set_border_width(6)
Hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.add(Hbox)
self.button = Gtk.Button("Open dialog")
self.button.connect("clicked", self.on_button_clicked)
Hbox.pack_start(self.button, True, True, 0)
self.progressbar = Gtk.ProgressBar()
Hbox.pack_start(self.progressbar, True, True, 0)
#~~~~~~ Progress Bar
def on_timeout(self, user_data):
"""
Update value on the progress bar
"""
if self.activity_mode:
self.progressbar.pulse()
else:
new_value = self.progressbar.get_fraction() + 0.01
if new_value > 1:
new_value = 0
self.progressbar.set_fraction(new_value)
# As this is a timeout function, return True so that it
# continues to get called
return True
def on_button_clicked(self, widget):
dialog = DialogExample(self)
response = dialog.run()
if response == Gtk.ResponseType.OK:
variable = dialog.Myinput.get_text()
print("start")
dialog.destroy()
#ProgressBar time function
self.timeout_id = GObject.timeout_add(50, self.on_timeout, None)
self.activity_mode = False
self.progressbar.pulse()
#this for Updating the Windows and make the progressbar pulsing while waiting
# the class ABCD finish his stuff, finally should stop pulsing.
while Gtk.events_pending():
Gtk.main_iteration_do(False)
passing_instance = ABCD(variable)
class ABCD(object):
def __init__(self,value_of_dialog):
self.get_value = value_of_dialog
self.for_add = "______ add was done"
self.final_value = self.get_value+self.for_add
time.sleep(10)
print("gonna be finished")
print(self.final_value)
win = DialogWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
As we can see here i already try to make pulse and refresh the windows in this part of code
self.timeout_id = GObject.timeout_add(50, self.on_timeout, None)
self.activity_mode = False
self.progressbar.pulse()
#this for Updating the Windows and make the progressbar pulsing while waiting
# the class ABCD finish his stuff, finally should stop pulsing.
while Gtk.events_pending():
Gtk.main_iteration_do(False)
Otherwise because in my class ABCD() i have time.sleep(10) should
the progress bar pulse only for that time 10 seconds later only then
stop.
How should this code gonna be, i need someone provide me the correct code, with little explain.
The issue with using sleep in order to emulate the passing of time is that sleep will stop everything that is happening in the thread which in this case prevents the thread to reach Gtk.main() which is needed to make your progressbar pulse or update.
So in order to do this properly there are 2 options:
Run ABCD in a separate thread such that the main thread can reach Gtk.main(). Which than will make sure that the progressbar moves as expected. A quick example of this looks like this:
self.abcd_thread = ABCD(variable)
self.abcd_thread.start()
class ABCD(Thread):
def __init__(self, value_of_dialog):
super(ABCD, self).__init__()
self.get_value = value_of_dialog
self.for_add = "______ add was done"
self.final_value = self.get_value+self.for_add
def run(self):
print "Starting " + self.name
time.sleep(10)
print("gonna be finished")
print(self.final_value)
print "Exiting " + self.name
When using this you can use self.abcd_thread.isAlive() to see whether the thread is still computing things. The way to return information heavily depends on the job placed in the thread.
Replace the time.sleep with the following fragment:
now = time.time()
while time.time() - now < 10:
# Insert any code here
Gtk.main_iteration_do(False)
This will still emulate ABCD doing stuff for 10 seconds but because we call Gtk.main_iteration_do(False) in each iteration of the loop GTK is able to update the interface during the loop.
In general the second option is the easiest as it only involves making Gtk.main_iteration_do(False) call during whatever your doing. The first option on the other hand is more useful when dealing with complex computations where adding Gtk calls doesn't fit in easily.

collidesWithItem() function not detecting collision (PyQt)

I'm writing an application that allows the user to add items to a scene. I dont want any new items being drawn over items that have already been drawn and to do that I decided to use the collidesWithItem() function to detect collision. With my code i still can draw over added items even though there is obviously collision and I debugged the program and the collidesWithItem() function keeps returning "False".
The items are added by clicking on the toolbar of the Form.
Down below is my code:
class graphicsScene(QtGui.QGraphicsScene, QtGui.QWidget):
def __init__(self, parent=None):
super(graphicsScene, self).__init__(parent)
self.i = 0
self.setSceneRect(-180, -90, 360, 180)
global overlapped
overlapped = 0
def mousePressEvent(self, event):
global host_cs
global overlapped
if host_cs == 1:
if len(hostItem_list) == 0:
self.host_item = host_Object()
hostItem_list.append(self.host_item.host_pixItem)
else:
self.host_item = host_Object()
for host in hostItem_list:
if self.host_item.host_pixItem.collidesWithItem(host):
print 'collision'
overlapped = 1
break
elif self.host_item.host_pixItem.collidesWithItem(host) == False:
overlapped = 0
if overlapped == 0:
hostItem_list.append(self.host_item.host_pixItem)
def mouseReleaseEvent(self, event):
global host_cs
if host_cs == 1:
if overlapped == 0:
self.addItem(self.host_item.host_pixItem)
self.host_item.host_pixItem.setPos(event.scenePos())
self.i += 1
host_list.append('h' + str(self.i))
class host_Object(QtGui.QGraphicsPixmapItem, QtGui.QWidget):
def __init__(self, parent=None):
super(host_Object, self).__init__(parent)
pixmap = QtGui.QPixmap("host.png")
self.host_pixItem = QtGui.QGraphicsPixmapItem(pixmap.scaled(30, 30, QtCore.Qt.KeepAspectRatio))
self.host_pixItem.setFlag(QtGui.QGraphicsPixmapItem.ItemIsSelectable)
self.host_pixItem.setFlag(QtGui.QGraphicsPixmapItem.ItemIsMovable)
class Form(QtGui.QMainWindow, QtGui.QWidget):
def __init__(self):
super(Form, self).__init__()
self.ui = uic.loadUi('form.ui')
self.ui.actionHost.triggered.connect(self.place_host)
self.scene = graphicsScene()
self.ui.view.setScene(self.scene)
def place_host(self):
host_cs = 1
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
form = Form()
form.ui.show()
app.exec_()
Multiple inheritance is source of all evil things in application design.
Also it is forbidden in Qt to double inherit QObject.
So all your classes with multiple inheritance has big flaws.
Even class host_Object(QtGui.QGraphicsPixmapItem, QtGui.QWidget) is wrong and problematic since item can't be a QWidget and QGraphicsItem at the same time.
I would recommend you to avoid double inheritance as a general rule not only for Qt framework but for any language.

How to stop a QThread from the GUI

This is a follow up question to a previous one I posted earlier.
The problem is how to stop (terminate|quit|exit) a QThread from the GUI when using the recommended method of NOT subclassing Qthread, but rather vreating a QObject and then moving it to a QThread. Below if a working example. I can start the GUI and the Qthread and I can have the latter update the GUI. However, I cannot stop it. I tried several methods for qthread (quit(), exit(), and even terminate()) to no avail.
Help greatly appreciated.
Here is the complete code:
import time, sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class SimulRunner(QObject):
'Object managing the simulation'
stepIncreased = pyqtSignal(int, name = 'stepIncreased')
def __init__(self):
super(SimulRunner, self).__init__()
self._step = 0
self._isRunning = True
self._maxSteps = 20
def longRunning(self):
while self._step < self._maxSteps and self._isRunning == True:
self._step += 1
self.stepIncreased.emit(self._step)
time.sleep(0.1)
def stop(self):
self._isRunning = False
class SimulationUi(QDialog):
'PyQt interface'
def __init__(self):
super(SimulationUi, self).__init__()
self.goButton = QPushButton('Go')
self.stopButton = QPushButton('Stop')
self.currentStep = QSpinBox()
self.layout = QHBoxLayout()
self.layout.addWidget(self.goButton)
self.layout.addWidget(self.stopButton)
self.layout.addWidget(self.currentStep)
self.setLayout(self.layout)
self.simulRunner = SimulRunner()
self.simulThread = QThread()
self.simulRunner.moveToThread(self.simulThread)
self.simulRunner.stepIncreased.connect(self.currentStep.setValue)
self.stopButton.clicked.connect(simulThread.qui) # also tried exit() and terminate()
# also tried the following (didn't work)
# self.stopButton.clicked.connect(self.simulRunner.stop)
self.goButton.clicked.connect(self.simulThread.start)
self.simulThread.started.connect(self.simulRunner.longRunning)
self.simulRunner.stepIncreased.connect(self.current.step.setValue)
if __name__ == '__main__':
app = QApplication(sys.argv)
simul = SimulationUi()
simul.show()
sys.exit(app.exec_())
I know its long ago but i just stumbled over the same problem.
I have been also searching for an appropriate way to do this. Finally it was easy. When exiting the application the task needs to be stopped and the thread needs to be stopped calling its quit method. See stop_thread method on bottom. And you need to wait for the thread to finish. Otherwise you will get QThread: Destroyed while thread is still running' message at exit.
(I also changed my code to use pyside)
import time, sys
from PySide.QtCore import *
from PySide.QtGui import *
class Worker(QObject):
'Object managing the simulation'
stepIncreased = Signal(int)
def __init__(self):
super(Worker, self).__init__()
self._step = 0
self._isRunning = True
self._maxSteps = 20
def task(self):
if not self._isRunning:
self._isRunning = True
self._step = 0
while self._step < self._maxSteps and self._isRunning == True:
self._step += 1
self.stepIncreased.emit(self._step)
time.sleep(0.1)
print "finished..."
def stop(self):
self._isRunning = False
class SimulationUi(QDialog):
def __init__(self):
super(SimulationUi, self).__init__()
self.btnStart = QPushButton('Start')
self.btnStop = QPushButton('Stop')
self.currentStep = QSpinBox()
self.layout = QHBoxLayout()
self.layout.addWidget(self.btnStart)
self.layout.addWidget(self.btnStop)
self.layout.addWidget(self.currentStep)
self.setLayout(self.layout)
self.thread = QThread()
self.thread.start()
self.worker = Worker()
self.worker.moveToThread(self.thread)
self.worker.stepIncreased.connect(self.currentStep.setValue)
self.btnStop.clicked.connect(lambda: self.worker.stop())
self.btnStart.clicked.connect(self.worker.task)
self.finished.connect(self.stop_thread)
def stop_thread(self):
self.worker.stop()
self.thread.quit()
self.thread.wait()
if __name__ == '__main__':
app = QApplication(sys.argv)
simul = SimulationUi()
simul.show()
sys.exit(app.exec_())
I found out that my original question was actually two questions in one: in order to stop a secondary thread from the main one, you need two things:
Be able to communicate from the main thread down to the secondary thread
Send the proper signal to stop the thread
I haven't been able to solve (2), but I figured out how to solve (1), which gave me a workaround to my original problem. Instead of stopping the thread, I can stop the thread's processing (the longRunning() method)
The problem is that a a secondary thread can only respond to signals if it runs its own event loop. A regular Qthread (which is what my code used) does not. It is easy enough, though, to subclass QThread to that effect:
class MyThread(QThread):
def run(self):
self.exec_()
and used self.simulThread = MyThread() in my code instead of the original self.simulThread = Qthread().
This ensures that the secondary thread runs an event loop. That was not enough, though. The longRunning() method needs to have a chance to actually process the event coming down from the main thread. With the help of this SO answer I figured out that the simple addition of a QApplication.processEvent() in the longRunning() method gave the secondary thread such a chance. I can now stop the processing carried out in the secondary thread, even though I haven't figured out how to stop the thread itself.
To wrap up. My longRunning method now looks like this:
def longRunning(self):
while self._step < self._maxSteps and self._isRunning == True:
self._step += 1
self.stepIncreased.emit(self._step)
time.sleep(0.1)
QApplication.processEvents()
and my GUI thread has these three lines that do the job (in addition to the QThread subclass listed above):
self.simulThread = MyThread()
self.simulRunner.moveToThread(self.simulThread)
self.stopButton.clicked.connect(self.simulRunner.stop)
Comments are welcome!
You can stop the thread by calling exit() or quit() . In extreme cases, you may want to forcibly terminate() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for terminate() and setTerminationEnabled() for detailed information.
src: https://doc.qt.io/qtforpython/PySide2/QtCore/QThread.html

Categories

Resources