PyQt5 Gui Freezes

49 Views Asked by At
import sys
from PyQt5 import QtWidgets
from tablo import Ui_MainWindow
from PyQt5.QtWidgets import QMessageBox, QVBoxLayout
from PyQt5.QtCore import QThread, pyqtSignal, QDate, QUrl, Qt, QTimer
from data import Tablolar
from PyQt5.QtWebEngineWidgets import QWebEngineView
import logging
import random
import cProfile
import time

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    handlers=[logging.FileHandler("selam_log.log"), logging.StreamHandler()])

class ChooseAnalysis:
    def __init__(self, main_window):
        self.main_window = main_window
        self.setup_connections()

    def setup_connections(self):
        self.main_window.ui.adin_buton.clicked.connect(self.adin_buton_clicked)

    def adin_buton_clicked(self):
        self.main_window.ui.stackedWidget.setCurrentIndex(2)


class AdinPage:
    def __init__(self, main_window):
        self.main_window = main_window
        self.setup_connections()

    def setup_connections(self):
        self.main_window.ui.tablo_buton.clicked.connect(self.tablo_buton_clicked)

    def tablo_buton_clicked(self):
        self.main_window.ui.stackedWidget.setCurrentIndex(3)

class DashThread(QThread):
    finished = pyqtSignal()  # Thread bitiş sinyali

    def __init__(self, func, args, thread_name):
        super(DashThread, self).__init__()
        self.func = func
        self.args = args
        self.thread_name = thread_name  # Thread için benzersiz bir isim


    def run(self):
        logging.info(f"{self.func.__name__} thread başlıyor.")
        self.func(*self.args)
        logging.info(f"{self.func.__name__} thread bitti.")
        self.finished.emit()

    def stop(self):
        logging.info(f"{self.func.__name__} thread durduruluyor.")
        self.terminate()

class TabloAcimlari:
    def __init__(self, main_window):
        self.ui = main_window.ui
        self.tablolar = Tablolar()
        self.initializeUI()
        self.dashboard_thread = None
        self.current_port = None
        self.active_threads = []


    def initializeUI(self):
        self.layout = QVBoxLayout(self.ui.tablo_widget)
        self.ui.tablo_widget.setLayout(self.layout)
        self.web_view = QWebEngineView(self.ui.tablo_widget)
        self.layout.addWidget(self.web_view)

        self.tablo_combobox = self.ui.tablo_combo

        tablo_isimleri = [
            'tablo1',
            'tablo2'
        ]

        self.tablo_combobox.addItems(tablo_isimleri)


        self.baslangic_tarihi = self.ui.baslangic_tarihi.date().toString("yyyy-MM-dd")
        self.bitis_tarihi = self.ui.bitis_tarihi.date().toString("yyyy-MM-dd")

        baslangic_tarihi = QDate(2023, 7, 10)
        bitis_tarihi = QDate(2023, 7, 17)

        self.ui.baslangic_tarihi.setDate(baslangic_tarihi)
        self.ui.bitis_tarihi.setDate(bitis_tarihi)

        self.ui.tabloyu_goster.clicked.connect(self.tabloyu_goster)

    def tabloyu_goster(self):
        start_time = time.time()
        self.baslangic_tarihi = self.ui.baslangic_tarihi.date().toString("yyyy-MM-dd")
        self.bitis_tarihi = self.ui.bitis_tarihi.date().toString("yyyy-MM-dd")

        self.current_port = random.randint(2000, 8000)

        selected_tablo = self.ui.tablo_combo.currentText()
        if selected_tablo == "tablo1":
            thread_name = f"DashboardThread_{selected_tablo}"
            self.dashboard_thread = DashThread(self.tablolar.tablo1,
                                               (self.baslangic_tarihi, self.bitis_tarihi, self.current_port), thread_name)
        elif selected_tablo == "tablo2":
            thread_name = f"DashboardThread_{selected_tablo}"
            self.dashboard_thread = DashThread(self.tablolar.tablo2,
                                               (self.baslangic_tarihi, self.bitis_tarihi, self.current_port), thread_name)
        else:
            return

        if self.dashboard_thread and self.dashboard_thread.isRunning():
            logging.info(f"Thread {self.dashboard_thread.thread_name} sonlandiriliyor.")
            self.dashboard_thread.terminate()
            self.dashboard_thread.wait()
            logging.info(f"Thread {self.dashboard_thread.thread_name} basariyla sonlandirildi.")

        for thread in self.active_threads:
            if thread.isRunning():
                logging.info(f"Thread {thread.thread_name} sonlandiriliyor.")
                thread.terminate()
                thread.wait()
                logging.info(f"Thread {thread.thread_name} basariyla sonlandirildi.")

        # Thread'i başlat
        logging.info(f"{selected_tablo} thread baslatiliyor.")
        self.dashboard_thread.start()

        self.active_threads.append(self.dashboard_thread)

        yukleme_html = """
                <html>
    <head>
        <style>
            .loader {
                border: 5px solid #f3f3f3;  /* Light grey */
                border-top: 5px solid #3498db;  /* Blue */
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        </style>
    </head>
    <body>
        <div style="text-align:center;">
            <div class="loader"></div>
            <h2>Tablo Oluşturuluyor Lütfen Bekleyiniz...</h2>
        </div>
    </body>
</html>
                """
        self.web_view.setHtml("<h2>Tablo Oluşturuluyor Lütfen Bekleyiniz...</h2><div class='loader'></div>")

        url = f"http://localhost:{self.current_port}"
        self.web_view.load(QUrl(url))

        QTimer.singleShot(500, lambda: self.web_view.load(QUrl(url)))

        end_time = time.time()
        total_time = end_time - start_time
        logging.info(f"tabloyu_goster metodunun calisma süresi: {total_time} saniye.")


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.giris_buton.clicked.connect(self.giris_yap)
        self.ui.stackedWidget.setCurrentIndex(0)

        self.ui.username_line.returnPressed.connect(self.giris_yap)
        self.ui.pass_line.returnPressed.connect(self.giris_yap)

        self.choose_analysis = ChooseAnalysis(self)
        self.adin_page = AdinPage(self)
        self.tablo_acimlari = TabloAcimlari(self)

    def closeEvent(self, event):
        logging.info("Pencere kapatiliyor.")
        for thread in self.tablo_acimlari.active_threads:
            if thread.isRunning():
                logging.info(f"Thread {thread.thread_name} kapatiliyor.")
                thread.terminate()
                thread.wait()
                logging.info(f"Thread {thread.thread_name} basariyla kapatildi.")
            else:
                logging.info(f"Thread {thread.thread_name} zaten kapali.")
        event.accept()

    def giris_yap(self):
        kullanici_adi = self.ui.username_line.text()
        sifre = self.ui.pass_line.text()

        if kullanici_adi == "adin" and sifre == "adin":
            self.ui.stackedWidget.setCurrentIndex(1)
        else:
            QMessageBox.warning(self, "Hata", "Geçersiz kullanıcı adı veya şifre!")


def main():
    app = QtWidgets.QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    cProfile.run('main()', 'output_file.prof')

Hello everyone. I am creating a python interface. In my code, there is a page called tablo_acimlari and I perform the operations of this page in the class called TabloAcimlari. What I do in this class is this: I want to make the user select a start and end date, select a combo box value, run a function according to the selected values and open the url that is the output of the function running on the screen with QWebEngineView. Currently, these operations are happening in this code and the url appears in the widget. However, there is a problem: when I select the values and click on the pushButton named table_goster, sometimes the interface freezes and I can't find the reason for weeks. Can you help me with this issue?

0

There are 0 best solutions below