0

I'm having an personal issue with threads in PyQt6. I have used the great example in the solution of How to stop a QThread from the GUI and rebuilt it with a separate dialog and a finished event.

In theory, what I am trying to create is a Connection Dialog which opens a database connection with oracledb. Although, if I click on the connection in the connection dialog, it should not connect silently, but it rather should display a Cancel Dialog, where if I want, I can choose to cancel the current connection attempt. This functionality should later then be used for every query against the database in my program, the connection dialog was just an example.

My current issue is, that the button on the Cancel Dialog is not displayed. Somehow the Cancel Dialog is frozen even though I use threads for the worker to connect.

For this I have created the following reduced code example:

import time

from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *


class ConnectionDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.database = -1
        self.setFixedSize(QSize(200, 100))

        # create CancelDialog but do not display yet
        self.cancel_dialog = CancelDialog(self)

        # creat a thread
        self.thread = QThread()
        self.thread.start()

        # creat a worker and put it on thread
        self.worker = Worker()
        self.worker.moveToThread(self.thread)

        # create button which triggers the cancel_dialog and therefore the connection attempt
        self.btnStart = QPushButton("Connect")
        self.btnStart.clicked.connect(self.start_worker)

        # if the worker emits finished call helper function end_thread
        self.worker.finished.connect(self.end_thread)

        # create dummy layout to display the button
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.btnStart)
        self.setLayout(self.layout)

    # helper function to quit and wait for the thread
    def end_thread(self, connection):
        self.worker.stop()
        self.thread.quit()
        self.thread.wait()
        print(f"Connected to {connection}")
        self.close()
        # push connection to self.database for further use
        self.database = connection

    # helper function to start worker in thread
    def start_worker(self):
        self.cancel_dialog.show()
        self.worker.task()


class CancelDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setModal(True)
        # create button for the cancel operation for the thread of the parent
        self.btnStop = QPushButton("Cancel")
        self.btnStop.clicked.connect(lambda: self.cancel_thread())

        # create dummy layout to display the button
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.btnStop)
        self.setLayout(self.layout)

    # helper function when pressing cancel button
    def cancel_thread(self):
        # stop worker
        self.parent().worker.stop()
        # quit thread, this time we dont want to wait for the thread
        self.parent().thread.quit()
        print("Canceled")
        self.close()
        # push error value to self.database
        self.parent().database = -1


class Worker(QObject):
    "Object managing the simulation"
    finished = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self._isRunning = True
        self.connection = -1

    def task(self):
        if not self._isRunning:
            self._isRunning = True
        # this simulates a database connection
        print("connecting...")
        print("fake delay before connection")
        time.sleep(3)
        print("really connecting now")
        self.connection = 123
        print("fake delay after connection")
        time.sleep(3)
        print("really connecting now")
        self.finished.emit(self.connection)
        print("finished connecting")

    def stop(self):
        self._isRunning = False
        if self.connection:
            self.connection = 0
            print("Canceled")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    simul = ConnectionDialog()
    simul.show()
    sys.exit(app.exec())
krstn420
  • 3
  • 3
  • 1
    You're starting the worker in the main thread, so it will block. You need to connect the thread's `started` signal to the worker's `task` slot, and only call `thread.start()` inside the `start_worker` slot. Thus, the thread will then start the worker once its event-loop starts. – ekhumoro Feb 18 '23 at 23:02
  • thank you so much, you pushed me in the right direction, i made it work! check out my solution below, maybe you have more input on this :) – krstn420 Feb 19 '23 at 00:48

1 Answers1

0

I did some more research because I had some more errors, the comment of ekhumoro was also VERY helpful. I removed workers altogether and only used a class that inherits from QThread. i added another signal "started" to determine when to show the cancel dialog. maybe this is use to somebody someday :)

this is the final reduced code example:

import sys
import time

from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *


class ConnectionDialog(QDialog):
    def __init__(self):
        super().__init__()
        self.database = None
        self.setFixedSize(QSize(200, 100))

        # create CancelDialog but do not display yet
        self.cancel_dialog = CancelDialog(self)

        # creat a thread
        self.thread = BackgroundThread()

        # create button which triggers the cancel_dialog and therefore the connection attempt
        self.btnStart = QPushButton("Connect")
        self.btnStart.clicked.connect(self.thread.start)

        # if started signals, show cancel_dialog
        self.thread.started.connect(self.cancel_dialog.show)
        # if finished signals, end thread and close cancel_dialog
        self.thread.finished.connect(self.end_thread)
        self.thread.finished.connect(self.cancel_dialog.close)

        # create dummy layout to display the button
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.btnStart)
        self.setLayout(self.layout)

    # helper function to quit and wait for the thread
    def end_thread(self, connection):
        self.thread.quit()
        self.thread.wait()
        print(f"Connected to {connection}")
        # push connection to self.database for further use
        self.database = connection
        self.close()

class CancelDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.setModal(True)
        # create button for the cancel operation for the thread of the parent
        self.btnStop = QPushButton("Cancel")
        self.btnStop.clicked.connect(lambda: self.cancel_thread())

        # create dummy layout to display the button
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.btnStop)
        self.setLayout(self.layout)

    # helper function when pressing cancel button
    def cancel_thread(self):
        # terminate thread (Warning, see documentation)
        self.parent().thread.terminate()
        print("Canceled thread")
        # push error value to self.database
        self.parent().database = None
        self.close()

class BackgroundThread(QThread):
    finished = pyqtSignal(int)
    started = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        self.started.emit()
        print("connecting...")
        print("fake delay before connection")
        time.sleep(3)
        print("really connecting now")
        self.connection = 123
        print("fake delay after connection")
        time.sleep(3)
        print("done")
        self.finished.emit(self.connection)
        print("finished connecting")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    simul = ConnectionDialog()
    simul.show()
    ret = app.exec()
    if simul.database:
        print("Accepted")
    else:
        print("Rejected")
    print(simul.database)
krstn420
  • 3
  • 3