1 year ago

#250533

test-img

abubasil

PyQt5; Problem with QRunnable and QThreadPool

Referring to:

How to pass parameters to PyQt QThreadPool running function

I am trying to apply the above topic to my code to avoid GUI freezing, the issue that fails to create a pushbutton within the TableWedgit in fn(push) and (setCellWidget) when using the fn(Run) when pressing "PushButton", while it is fine with fn(run) when pressing"RadioButton" with a GUI freezing.

All the files are available via the link:

https://drive.google.com/file/d/1fE7NkX9y1SFTHDuZWZZxh_NiL-msiZbT/view?usp=sharing

import os
import sys
import traceback
from time import sleep

import openpyxl
import pandas
import pandas as pd
import xlsxwriter
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from openpyxl import load_workbook

from loop_150 import Ui_Form

class WorkerSignals(QObject):
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
    progress = pyqtSignal(int)

class Worker(QRunnable):

    def __init__(self, fn):
        super(Worker, self).__init__()

        self.fn = fn
        self.signals = WorkerSignals()


    @pyqtSlot()
    def run(self):
       try:
            result = self.fn()
       except Exception as e:
           print('Worker(QRunnable):', e)

class PushButton(QtWidgets.QPushButton):
    def __init__(self, object_name):
        super(PushButton, self).__init__()
        self.setObjectName(str(object_name))

class Form(QWidget, Ui_Form):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)

        self.radioButton.clicked.connect(self.run)
        self.pushButton.clicked.connect(self.Run)
        self.tableWidget_1.itemChanged.connect(self.ItemChanged)

        self.threadpool = QThreadPool()

    def run(self):
        df0 = self.excel_to_df('trade_ratio_dffx0')
        df1 = self.excel_to_df('trade_ratio_dffx1')
        df2 = self.excel_to_df('trade_ratio_dffx2')
        df3 = self.excel_to_df('trade_ratio_dffx3')
        i = 0
        x = 0
        y =1
        z =2
        m = 3

        self.previous_item = []
        while i < 10:
            self.textBrowser.append(str(i))
            app.processEvents()
            sleep(1)

            if i == x:
                df = df3
            if i == y:
                df = df1
            if i == z:
                df = df2
            if i == m:
                df = df0
                x += 4
                y += 4
                z += 4
                m += 4

            i += 1
            table = self.tableWidget_1
            self.table_view(df, table)
            self.push()
            self.previous_item = []
            for items in df['balance']:
                self.previous_item.append(items)
            app.processEvents()
    def Run(self):
        worker = Worker(self.run)
        self.threadpool.start(worker)

    def push(self):
        try:
            for row in range(1, self.tableWidget_1.rowCount()):
                pushButton = PushButton(row)
                self.tableWidget_1.setCellWidget(row, 3, pushButton)
                r = self.tableWidget_1.item(row, 3).text()
                if float(r) > 0:
                    pushButton.setStyleSheet("background:rgb(0, 188, 138);color:rgb(255, 255, 255)")
                elif float(r) == 0:
                    pushButton.setStyleSheet("background:rgb(185, 185, 185);color:rgb(255, 255, 255)")
                else:
                    pushButton.setStyleSheet("background:rgb(255, 5, 72);color:rgb(255, 255, 255)")
                pushButton.setText(r + '%')
        except Exception as e:
            print('push', e)
    def ItemChanged(self, item):
        try:
            for row in range(1, self.tableWidget_1.rowCount()):
                if item.column() == 1 and self.tableWidget_1.item(row, 1).text() != None:
                    if float(self.tableWidget_1.item(row, 1).text()) < 0:
                        self.tableWidget_1.item(row, 1).setForeground(QColor(255, 0, 100, 200))
                    elif float(self.tableWidget_1.item(row, 1).text()) > 0:
                        self.tableWidget_1.item(row, 1).setForeground(QColor(0, 222, 122, 222))
                    elif float(self.tableWidget_1.item(row, 1).text()) == 0:
                        self.tableWidget_1.item(row, 1).setForeground(QColor(0, 0, 0, 150))
        except:
            pass
  
    def excel_to_df(self, wbkName):
        while True:
            try:
                wbkName = wbkName + ".xlsx"
                df = pd.read_excel(wbkName)
                try:
                    df = df.drop(columns=['Index'])
                except:
                    pass
                try:
                    df = df.drop(columns=['index'])
                except:
                    pass
                try:
                    df = df.drop(columns=[0])

                except:
                    pass
                try:
                    df = df.drop(columns=['Unnamed: 0'])
                except:
                    pass
                try:
                    df = df.drop(columns=['Unnamed'])
                except:
                    pass
                try:
                    df = df.drop(columns=['0'])
                except:
                    pass
                try:
                    df = df.drop(columns=['Unnamed:'])
                except:
                    pass
                return df
            except:
                pass
    def table_view(self, df, table):
        col_number = len(df.columns)
        table.setColumnCount(col_number)
        table.setRowCount(0)
        table.insertRow(0)
        for row_number in range(len(df)):
            table.insertRow(row_number + 1)
            for col_number, col_data in enumerate(df):
                table.setItem(0, col_number, QtWidgets.QTableWidgetItem(str(col_data)))
                table.setItem(row_number + 1, col_number, QtWidgets.QTableWidgetItem(str(df[col_data][row_number])))
                header = table.horizontalHeader()
                header.setSectionResizeMode(col_number, QtWidgets.QHeaderView.Stretch)

app = QApplication(sys.argv)
window = Form()
window.show()
app.exec_()

python

multithreading

pyqt5

qt-designer

qrunnable

0 Answers

Your Answer

Accepted video resources