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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...