How to connect functions to PyQt signals outside of main thread - python

I'm creating a PyQt app where I want to have a background thread that connects some event handlers and then loops forever until the main window is closed. The problem I am experiencing is that the event handlers I am connecting only work if they are functions defined inside my MainWindow class. I have created a minimal repro below:
import threading
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QVBoxLayout
class MainWindow(QDialog):
def __init__(self):
super(MainWindow, self).__init__()
self.button1 = QPushButton("Click Me", self)
self.button2 = QPushButton("Me Too!", self)
layout = QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
self.setLayout(layout)
def test(self):
print("test inside class")
def test2():
print("test outside class")
def main(window):
window.button1.clicked.connect(window.test)
window.button2.clicked.connect(test2)
# Loop that runs in thread...
app = QApplication([])
window = MainWindow()
window.show()
threading.Thread(target=main, args=[window]).start()
app.exec_()
When I run this code, the first button prints a message to the console as expected, but the second one does nothing when clicked. If I run the main(window) function in the main thread, then both buttons work. I'm aware that in my small sample program this would be the obvious solution, but for reasons that are complex to explain I need to be able to connect the event handlers from the background thread in my application. Why does connecting a function like test2() that is defined outside the MainWindow class not work when I do it outside of the main thread?

I'm still finding out the reason for the problem but the solution is to indicate the type of connection, in this case Qt::DirectConnection that will make the function test2 run on the same thread of the object that emits the signal (the object that emits the signal is the button that lives in the main thread).
import threading
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QDialog):
def __init__(self):
super(MainWindow, self).__init__()
self.button1 = QtWidgets.QPushButton("Click Me")
self.button2 = QtWidgets.QPushButton("Me Too!")
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button1)
layout.addWidget(self.button2)
#QtCore.pyqtSlot()
def test(self):
print("test inside class")
def test2():
print("test outside class")
def main(window):
window.button1.clicked.connect(window.test)
window.button2.clicked.connect(test2, QtCore.Qt.DirectConnection)
while True:
QtCore.QThread.sleep(1)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
threading.Thread(target=main, args=(window,), daemon=True).start()
sys.exit(app.exec_())

Related

With PyQt5, implement two windows looping forever automatically

Using PyQt5, I want to implement a two windows displaying one after another automatically, without the user interacting with any window. Something like this:
While True:
Show Window1
wait 2 seconds
Close Window1
Show Window2
wait 2 seconds
Close Window2
The problem I am having is that the main UI thread is stuck in app.exec_() function, so it cannot implement the opening and closing logic.
import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
class Win1(QMainWindow):
def __init__(self):
super(Win1, self).__init__()
uic.loadUi('win1.ui', self)
self.show()
class Win2(QMainWindow):
def __init__(self):
super(Win2, self).__init__()
uic.loadUi('win2.ui', self)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
while True:
win = Win1()
time.sleep(1)
win.close()
win = Win2()
time.sleep(1)
win.close()
app.exec_() # <--------- Program blocks here
I would appreciate if someone can share a minimal example for this working without blocking. Or please point to the mechanism that should be used.
If you are going to work with Qt then you should forget about sequential logic but you have to implement the logic using events. For example, in your case you want one window to be shown every time T and another to be hidden, so that can be implemented with a QTimer and a flag:
import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic
class Win1(QMainWindow):
def __init__(self):
super(Win1, self).__init__()
uic.loadUi('win1.ui', self)
self.show()
class Win2(QMainWindow):
def __init__(self):
super(Win2, self).__init__()
uic.loadUi('win2.ui', self)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
timer = QTimer()
timer.setProperty("flag", True)
win1 = Win1()
win2 = Win2()
def on_timeout():
flag = timer.property("flag")
if flag:
win1.show()
win2.close()
else:
win2.show()
win1.close()
timer.setProperty("flag", not flag)
timer.timeout.connect(on_timeout)
timer.start(1 * 1000)
on_timeout()
app.exec_()
You should not use while loop or time.sleep since they block the eventloop in which the GUI lives, that is: they freeze the windows

Pyside2 second window(QDialog) closes the main one

import sys
from PySide2.QtCore import QFile
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtUiTools import QUiLoader
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
loader = QUiLoader()
self.ui = loader.load("mainWindow.ui", self)
self.ui.pushButton_call_dialog.clicked.connect(self.call_dialog)
self.ui.close()
self.ui.show()
def call_dialog(self):
loader = QUiLoader()
self.dialog = loader.load("dialog.ui")
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
window.show
sys.exit(app.exec_())
Hi everyone,
any idea why the second (dialog) window closes the entire application?
Of course, it is not a crash since i'm getting a message saying:
Process finished with exit code 0
Thanks for your help
You could handle your QDialog on a separate class, and then make them interact only, the structure might change a bit, but you can see if it's a viable answer:
import sys
from PySide2.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
button = QPushButton("Dialog")
button.clicked.connect(self.open_dialog)
self.setCentralWidget(button)
def open_dialog(self):
dialog = MyDialog()
dialog.show()
dialog.exec_()
class MyDialog(QDialog):
def __init__(self):
QDialog.__init__(self)
button = QPushButton("Close")
button.clicked.connect(self.close_dialog)
layout = QHBoxLayout()
layout.addWidget(button)
self.setLayout(layout)
def close_dialog(self):
self.close()
if __name__ == "__main__":
app = QApplication()
m = MyWindow()
m.show()
sys.exit(app.exec_())
Just notice that you should include the setUp step on each class.
Hope it helps.
To put the dialog into a separate class didn't work for either.
Every time the Dialog.close() event was called, it closes the whole application.
What worked for me, was to use hide() instead

Qt GUI inside loop?

What I want to achieve is a Qt Widget loop.
Simple example:
UI_dialog is a QDialog and after accepted it will open UI_mainwindow which is a QMainWindow.
There is a button in UI_mainwindow and if clicked, it will close UI_mainwindow and go back to UI_dialog.
What I've done so far:
I've tried:
create while loop in a Qthread which contains the two UI objects call UI_dialog inside UI_mainwindow (kind of succeed but may crash sometimes for my poor design)
In a GUI you must avoid the while True, the GUI already has an internal while True that allows you to listen to the events and according to it do the internal tasks. On the other hand the threads should be your last option since the GUI should not update from another thread directly, it should only be used if there is a blocking task.
In the case of Qt there are signals that allow notification of changes, this will be connected to functions so that the latter is invoked when the signal is emited.
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.button = QtWidgets.QPushButton("Press me")
self.setCentralWidget(self.button)
self.button.clicked.connect(self.close)
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
buttonBox = QtWidgets.QDialogButtonBox()
buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(buttonBox)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w1 = MainWindow()
w2 = Dialog()
w1.button.clicked.connect(w2.show)
w2.accepted.connect(w1.show)
w2.show()
sys.exit(app.exec_())

Python crashes with 2 worker threads in PyQt5 application

I would like to have 2 worker threads in my application. One should start running as soon as the GUI is loaded and another one should start later by some signal. Let's say it's a button click.
I came across a weird behavior when my Python interpreter crashes(as in shows me Windows error "Python stopped working", no stack trace) on executing the second thread.
Here is an example, that will crash right after I click the button.
class Worker(QtCore.QThread):
def __init__(self, method_to_run):
super().__init__()
self.method = method_to_run
def run(self):
self.method()
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QPushButton('Test', self)
self.label = QLabel(self)
self.button.clicked.connect(self.handleButton)
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.button)
self.worker = Worker(self.test_method)
self.worker.start()
def handleButton(self):
self.label.setText('Button Clicked!')
worker = Worker(self.test_method)
worker.start()
#staticmethod
def test_method():
res = [i*i for i in range(100500)]
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
What's more weird is that it doesn't crash when you debug the application for some reason.
What am I missing here?
Edit
I could get much from the crashdump, as I don't have symbols for QT. But it looks like the crash happens inside QtCore.dll
ExceptionAddress: 00000000632d4669 (Qt5Core!QThread::start+0x0000000000000229)
The problem is that you didn't save a reference to the thread so it was deleted as soon as you exited handleButton. If you save a reference, that begs the question of how to handle its lifespan.
QThread is more than just a wrapper to a system thread - it implements other services that let you wire a thread into your GUI. You can use its finished handler to signal the widget when it terminates to do any cleanup.
In this example, I save the worker as self.worker2 and block starting the worker a second time until the first one completes.
import PyQt5
import PyQt5.QtCore as QtCore
from PyQt5.QtWidgets import *
import time
class Worker(QtCore.QThread):
def __init__(self, method_to_run):
super(Worker, self).__init__()
self.method = method_to_run
def run(self):
self.method()
class Window(QWidget):
def __init__(self):
super().__init__()
self.button = QPushButton('Test', self)
self.label = QLabel(self)
self.button.clicked.connect(self.handleButton)
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.button)
self.worker = Worker(self.test_method)
self.worker.start()
self.worker2 = None
def handleButton(self):
self.label.setText('Button Clicked!')
# likely better to disable the button instead... but
# this shows events in action.
if self.worker2:
self.label.setText('Worker already running')
else:
self.worker2 = Worker(self.test_method)
self.worker2.finished.connect(self.handle_worker2_done)
self.worker2.start()
def handle_worker2_done(self):
self.worker2 = None
self.label.setText('Worker done')
#staticmethod
def test_method():
#res = [i*i for i in range(100500)]
time.sleep(3)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Your click triggered thread isn't actually trying to do work in a thread. You called the method, rather than passing the method as an argument, so you're trying to use the return value of test_method (None) as the method to run.
Change:
worker = Worker(self.test_method()) # Calls test_method and tries to run None
to:
worker = Worker(self.test_method) # Don't call test_method

Does closing a GUI in PyQt4 destroy its children Qobjects by default

I'm trying to make a GUI that used QTimer to create a state machine, but when ever I close the GUI window the timer continues. I think I'm properly making the object that creates my Qtimer a child of the GUI but with the behavior I'm seeing it doesn't seem like it. Here is some code
class Ui_Form(QtGui.QWidget):
def __init__(self):
super(Ui_Form, self).__init__()
self.backEnd = BackEnd(self)
self.backEnd.start()
class BackEnd(QtCore.QObject):
def __init__(self,parent=None):
super(BackEnd,self).__init__(parent)
self.setParent(parent)
self.timer = QtCore.QTimer()
self.timer.setSingleShot(True)
QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timerHandler)
def timerHandler(self):
print "Im here"
self.timer.start(1000)
def start(self):
self.timer.start(1000)
def stop(self):
self.timer.stop()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Timer does not continue when I close GUI window, it works fine, as desired... anyway, try to override close event for your Ui_Form like this:
def closeEvent(self):
self.backEnd.stop()
I hope that helps.
Also, I've changed your main like this:
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = Ui_Form()
ui.show()
sys.exit(app.exec_())
in your case it might be that Form = QtGui.QWidget() stays alive after you close GUI window. So try that modification first.

Categories