How to interrupt QThread from PyQt GUI? - user-interface

I'm writting an application that encrypt an image. The main problem is that i want to add to my GUI option to interrupt (or even terminate) an encrypting thread (while it is working) just by clicking an gui button. Gui and algorithm work fine (ia also provide a gui's progressbar connection) but when the thread start to procced i can't click anything on gui (even the terminating button). Beside that button is properly connected becuse if there occured an error in thread and gui i still working i can click the button and it terminate the process.
I thought that gui froze because thread was defined in gui function so I've moved it out of gui to main program function.
I want to point out that i don't create therad subclass (as Maya Posch suggest http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/)
Here is the code of main function:
def main():
app = QApplication(sys.argv)
cryptoThread = QtCore.QThread()
prog = ProgramWindow()
worker = ic.imageCryptographer()
worker.moveToThread(cryptoThread)
prog.progressButton.clicked.connect(lambda: prog.interruptEncrypting(cryptoThread))
prog.startEncrypting.connect(cryptoThread.start)
worker.encryptSignal.connect(prog.progressbar.setValue)
worker.done.connect(lambda: prog.endEncrypting(cryptoThread, worker))
cryptoThread.started.connect(lambda: worker.compute(prog.shareFlag, prog.binMatrix))
sys.exit(app.exec_())
functions from class ProgramWindow:
def interruptEncrypting(self, thread):
thread.terminate()
thread.wait()
self.interrupt()
return
def endEncrypting(self, thread, worker):
self.keys = worker.keys
thread.quit()
self.progressbarWidget.setVisible(False)
self.saveOption.setEnabled(True)
self.cryptoWorkdeskOption.setEnabled(True)
self.openCryptoWorkdesk()
def interrupt(self):
self.progressbarWidget.setVisible(False)
if self.state==1:
self.buttonSwapWidget.setVisible(True)
elif self.state==2:
self.keyChooseWidget.setVisible(True)
Variables: shareFlag and binMatrix has no connection to thread communication (their are variables necceseray to compute worker methods. StartEncrypting is a signal emited from one of ProgramWindow function.
Thanks in advance for any advice where I made a mistake or what should I do.

Yep, just tried it and can confirm what I already indicated in my comment. Although you moved worker to cryptoThread (and therefore all its methods) the moment you connect cryptoThread.started.connect(lambda: worker.compute(prog.shareFlag, prog.binMatrix)) you create a new lambda object which is not running within cryptoThread but within the main thread. That's why it does not run besides your main application. You would have to connect cryptoThread.started.connect(worker.compute) and pass the arguments in some additional initializer / configure method.
I tested it with the following code:
import sys
import time
from PyQt4 import QtGui, QtCore
class Worker(QtCore.QObject):
def __init__(self, parent=None):
QtCore.QObject.__init__(self, parent)
self.t1 = QtCore.QThread()
self.moveToThread(self.t1)
self.t1.start()
def do_stuff(self):
while True:
print 'loop'
time.sleep(1)
class MainWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.worker = Worker()
self.button = QtGui.QPushButton('start', self)
self.button.clicked.connect(self.worker.do_stuff) # connect directly with worker's method do_stuff
#self.button.clicked.connect(lambda: self.worker.do_stuff()) # connect with lambda object containing do_stuff
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

Related

pyQt6 + asyncio: connect an async function as a slot

I've got a situation where I would like to connect an async function that uses awaits to the clicked signal of a QPushButton.
The motivation is that I need to manage some io-bound stuff and using awaits seems to be the most cogent way to do that. The problem is that when one uses awaits, the invoking function needs to be marked as async and so do all functions that invoke THAT function. This "bubbles up to the top" until eventually, there's a button clicked signal that needs to be connected to an async slot function. I am not sure how to do that and there's not much advice. Maybe I got the wrong idea and pyQt6 isn't supposed to mix with asyncio?
Here's an example. It's just a QMainWindow with a button, and I am trying to connect the button's clicked signal to a slot function that happens to be async. It just prints numbers and uses asyncio.sleep(1.0) to wait for 1 second after printing each number.
import sys
import asyncio
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
button = QPushButton("Press This")
self.setCentralWidget(button)
button.clicked.connect(self.my_async_func)
async def my_async_func(self):
for x in range(1,10):
print(x)
await asyncio.sleep(1.0)
print("all done")
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
When I click the button I get the following, and of course, nothing prints.
RuntimeWarning: coroutine 'MainWindow.my_async_func' was never awaited
app.exec()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
How do I tell connect(...) that I want to use an async function?
My previous experience was coming from .net WPF and I was hoping that it would not be a big deal to tie an async function to a UI event.
OK, I found something that works without too much fussing.
I am not sure if it's correct. Please critique and, if possible, explain (I don't know enough about this).
The trick, for pyqt6, is to use qasync to create and start an event loop that async functions seem to be able to take as an argument. The async function also needs to be decorated with #asyncSlot().
import sys
import asyncio
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton
from qasync import QEventLoop, asyncSlot
class MainWindow(QMainWindow):
def __init__(self, loop=None):
super().__init__()
button = QPushButton("Press This")
self.setCentralWidget(button)
button.clicked.connect(self.my_async_func)
self.loop = loop or asyncio.get_event_loop()
#asyncSlot()
async def my_async_func(self):
for x in range(1,10):
print(x)
await asyncio.sleep(1.0,self.loop)
print("all done")
def main():
app = QApplication(sys.argv)
loop = QEventLoop(app)
asyncio.set_event_loop(loop)
window = MainWindow(loop)
window.show()
with loop:
loop.run_forever()
if __name__ == '__main__':
main()

How to display an icon in the systray reflecting NumLk state

My computer doesn't have any way of letting me know if my NumLk is on or off, so I am trying to add an icon in my systray that will changed depending on the state of my NumLk. This .py will always be running when my computer is on.
So far I was able to mix 3 codes and I am able to display the icon in the systray but it doesn't get updated when the state of NumLk change. Actually if I press NumLk twice, I still get the same icon (the on one) and I get this error:
QCoreApplication::exec: The event loop is already running
File "\systray_icon_NumLk_on_off.py", line 21, in on_key_press
main(on)
File "\systray_icon_NumLk_on_off.py", line 46, in main
sys.exit(app.exec_())
SystemExit: -1
My code may not be the best way to do it, so any alternative is welcome! Here is what I came up so far:
#####get the state of NumLk key
from win32api import GetKeyState
from win32con import VK_NUMLOCK
#how to use: print(GetKeyState(VK_NUMLOCK))
#source: http://stackoverflow.com/questions/21160100/python-3-x-getting-the-state-of-caps-lock-num-lock-scroll-lock-on-windows
#####Detect if NumLk is pressed
import pyglet
from pyglet.window import key
window = pyglet.window.Window()
#source: http://stackoverflow.com/questions/28324372/detecting-a-numlock-capslock-scrlock-keypress-keyup-in-python
on=r'on.png'
off=r'off.png'
#window.event
def on_key_press(symbol, modifiers):
if symbol == key.NUMLOCK:
if GetKeyState(VK_NUMLOCK):
#print(GetKeyState(VK_NUMLOCK))#should be 0 and 1 but
main(on)
else:
main(off)
#window.event
def on_draw():
window.clear()
### display icon in systray
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
#source: http://stackoverflow.com/questions/893984/pyqt-show-menu-in-a-system-tray-application - add answer PyQt5
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
pyglet.app.run()
The reason for QCoreApplication::exec: The event loop is already running is actually because you're trying to start app.run() twice. Qt will notice there's already an instance running and throw this exception. When instead, what you want to do is just swap the icon in the already running instance.
Your main problem here is actually the mix of libraries to solve one task if you ask me.
Rather two tasks, but using Qt5 for the graphical part is fine tho.
The way you use Pyglet is wrong from the get go.
Pyglet is intended to be a highly powerful and effective graphics library where you build a graphics engine ontop of it. For instance if you're making a game or a video-player or something.
The way you use win32api is also wrong because you're using it in a graphical window that only checks the value when a key is pressed inside that window.
Now, if you move your win32api code into a Thread (a QtThread to be precise) you can check the state no matter if you pressed your key inside your graphical window or not.
import sys
import win32api
import win32con
from PyQt5 import QtCore, QtGui, QtWidgets
from threading import Thread, enumerate
from time import sleep
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(QtWidgets.qApp.quit)
self.setContextMenu(menu)
class KeyCheck(QtCore.QThread):
def __init__(self, mainWindow):
QtCore.QThread.__init__(self)
self.mainWindow = mainWindow
def run(self):
main = None
for t in enumerate():
if t.name == 'MainThread':
main = t
break
while main and main.isAlive():
x = win32api.GetAsyncKeyState(win32con.VK_NUMLOCK)
## Now, GetAsyncKeyState returns three values,
## 0 == No change since last time
## -3000 / 1 == State changed
##
## Either you use the positive and negative values to figure out which state you're at.
## Or you just swap it, but if you just swap it you need to get the startup-state correct.
if x == 1:
self.mainWindow.swap()
elif x < 0:
self.mainWindow.swap()
sleep(0.25)
class GUI():
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
self.state = True
w = QtWidgets.QWidget()
self.modes = {
True : SystemTrayIcon(QtGui.QIcon('on.png'), w),
False : SystemTrayIcon(QtGui.QIcon('off.png'), w)
}
self.refresh()
keyChecker = KeyCheck(self)
keyChecker.start()
sys.exit(self.app.exec_())
def swap(self, state=None):
if state is not None:
self.state = state
else:
if self.state:
self.state = False
else:
self.state = True
self.refresh()
def refresh(self):
for mode in self.modes:
if self.state == mode:
self.modes[mode].show()
else:
self.modes[mode].hide()
GUI()
Note that I don't do Qt programming often (every 4 years or so).
So this code is buggy at it's best. You have to press Ctrl+C + Press "Exit" in your menu for this to stop.
I honestly don't want to put more time and effort in learning how to manage threads in Qt or how to exit the application properly, it's not my area of expertis. But this will give you a crude working example of how you can swap the icon in the lower corner instead of trying to re-instanciate the main() loop that you did.

Play image sequence using Qt QMainWindow

I have an image sequence rendered out. which I want to payback in a simple QMainWindow or QDialog. This is what I have sofar. It loads the images into the qlabel, but I cant see the label being updated, its just show the last loaded image, and nothing in between.
Maybe someone knows something?
from PySide import QtCore, QtGui
import shiboken
import maya.OpenMayaUI as apiUI
import time
def getMayaWindow():
"""
Get the main Maya window as a QtGui.QMainWindow instance
#return: QtGui.QMainWindow instance of the top level Maya windows
"""
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return shiboken.wrapInstance(long(ptr), QtGui.QWidget)
class Viewer(QtGui.QMainWindow):
def __init__(self, parent = getMayaWindow()):
super(Viewer, self).__init__(parent)
self.setGeometry(400, 600, 400, 300)
self.setUi()
def setUi(self):
self.label = QtGui.QLabel()
self.setCentralWidget(self.label)
def showUi(self):
self.show()
def loadImage(self, path):
self.label.clear()
image = QtGui.QImage(path)
pp = QtGui.QPixmap.fromImage(image)
self.label.setPixmap(pp.scaled(
self.label.size(),
QtCore.Qt.KeepAspectRatio,
QtCore.Qt.SmoothTransformation))
x = Viewer()
x.showUi()
for i in range(1, 11):
x.loadImage("C://anim%03d.png" % i)
time.sleep(0.5)
You change pixmaps in loop and sleep (stop) all GUI thread, that's why your GUI freeze.
http://www.tutorialspoint.com/python/time_sleep.htm
It is not correct. qLabel.repaint() it is bad solution because it still blocks GUI. Of course you can use processEvents but it is bad approach too.
You should use QTimer for this purpose, use timeout() signal, create slot and change pixmaps in this slot. In this case your GUI will not be blocked because QTimer works asynchronously and images will be successfuly changed.
Same code with loop and sleep can help you only when this code will execute in another thread (multi threading) but it is not necessary because there is special class QTimer.

What is a reasonable way of keeping track of multiple windows in PyQt?

I'm writing a PyQt application that shall feature multiple windows. Right now, I am interested in having one of two windows open at a time (so a click of a button in one window causes a switch to the other window). What is a reasonable way of keeping track of multiple windows in a PyQt application? My initial attempt, as shown below, essentially stores instances of the QtGui.QWidget in data members of a global instance of a simple class.
I'm new to PyQt. Is there a better way to approach this?
#!/usr/bin/env python
import sys
from PyQt4 import QtGui
class Program(object):
def __init__(
self,
parent = None
):
self.interface = Interface1()
class Interface1(QtGui.QWidget):
def __init__(
self,
parent = None
):
super(Interface1, self).__init__(parent)
self.button1 = QtGui.QPushButton(self)
self.button1.setText("button")
self.button1.clicked.connect(self.clickedButton1)
self.layout = QtGui.QHBoxLayout(self)
self.layout.addWidget(self.button1)
self.setGeometry(0, 0, 350, 100)
self.setWindowTitle('interface 1')
self.show()
def clickedButton1(self):
self.close()
program.interface = Interface2()
class Interface2(QtGui.QWidget):
def __init__(
self,
parent = None
):
super(Interface2, self).__init__(parent)
self.button1 = QtGui.QPushButton(self)
self.button1.setText("button")
self.button1.clicked.connect(self.clickedButton1)
self.layout = QtGui.QHBoxLayout(self)
self.layout.addWidget(self.button1)
self.setGeometry(0, 0, 350, 100)
self.setWindowTitle('interface 2')
self.show()
def clickedButton1(self):
self.close()
program.interface = Interface1()
def main():
application = QtGui.QApplication(sys.argv)
application.setApplicationName('application')
global program
program = Program()
sys.exit(application.exec_())
if __name__ == "__main__":
main()
Have a single main window with a QStackedWidget to hold the different interfaces. Then use QStackedWidget.setCurrentIndex to switch between the interfaces.
Also, try to avoid using global references. If you want GUI components to communicate with each other, use signals and slots. You can easily define your own custom signals if there are no suitable built-in ones.

How to get the details of an event in wxPython

I have a section of code which returns events generated by a slider.
I bind the event with self.Bind(wx.EVT_SCROLL,self.OnSlide).
The code which handles the event reads something like:
def OnSlide(self,event):
widget = event.GetEventObject()
This is great but an error gets thrown every time the code is executed. It reads:
AttributeError: 'PyEventBinder' object has no attribute 'GetEventObject'
I want to be able to see which of the sliders generated the event but the error appears every time I attempt to find out.
How can I get the code to execute correctly?
Many thanks in advance.
To debug something like this, put the following as the first statement in your event handler:
import pdb; pdb.set_trace()
This will stop the execution of the program at this point and give you an interactive prompt. You can then issue the following command to find out what methods are available:
print dir(event)
When I was first learning wxPython I found this technique invaluable.
The following works for me on Windows 7, wxPython 2.8.10.1, Python 2.5
import wx
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, title="Tutorial")
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
slider = wx.Slider(panel, size=wx.DefaultSize)
slider.Bind(wx.EVT_SLIDER, self.onSlide)
#----------------------------------------------------------------------
def onSlide(self, event):
""""""
obj = event.GetEventObject()
print obj
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()

Resources