Skip to main content

Cancel long running action with multiple dialogs in PyQt6

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())


source https://stackoverflow.com/questions/75496376/cancel-long-running-action-with-multiple-dialogs-in-pyqt6

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data