Pyqt5 dynamic startup interface

This article will introduce a Python program built using the PyQt5 library, which is mainly used to display the startup interface, connect to services in the background, and display the connection status. The program includes a startup interface, background data loading worker thread, and main interface. It achieves a smooth user experience by using the rich functions provided by the PyQt5 library.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File name: start.py
Function: Start the interface and call the main interface
"""
import time
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal
from PyQt5.QtGui import QFont, QMovie
from PyQt5.QtWidgets import QMainWindow, QSplashScreen
import requests
import json

class MySplashScreen(QSplashScreen):
    def __init__(self):
        super(MySplashScreen, self).__init__()
 
        # Start interface
        self.movie = QMovie('GMSCloudstart.gif')####Change to a dynamic image file made by yourself
        self.movie.frameChanged.connect(lambda: self.setPixmap(self.movie.currentPixmap()))
        self.movie.start()
 
    def mousePressEvent(self, QMouseEvent):
        pass
 
 
class LoadDataWorker(QObject):
    finished = pyqtSignal()
    message_signal = pyqtSignal(str)
 
    def __init__(self):
        super(LoadDataWorker, self).__init__()
 
    def run(self):
        self.message_signal.emit('Connecting to background service...')
        time.sleep(1)
        globalNETWORK_STATUS
        NETWORK_STATUS = True
        #----------------Put here some things that need to be loaded-------------------------------- ----------
        try:
            url = setting['ip']
            data = {"ask":"#ifstart"}
            res = requests.post(url=url,data=json.dumps(data),timeout=8)
            if res.status_code == 200:
                res_pro = json.loads(res.text)
                if res_pro['reply']=="ok":
                    self.message_signal.emit('The background service has been started and the connection was successful...')
                    time.sleep(1)
                    self.message_signal.emit('Starting graphical interface...')
                    self.finished.emit()
                else:
                    self.message_signal.emit('The background service connected successfully but did not reply correctly')
                    time.sleep(3)
                    self.finished.emit()
            else:
                self.message_signal.emit('Background service exception')
                time.sleep(3)
                self.finished.emit()
        except requests.exceptions.Timeout:
            self.message_signal.emit('The background service connection failed, the program will be closed')
            NETWORK_STATUS = False
            time.sleep(3)
            self.finished.emit()
        #------------------------------------------------ -------------------
 
class Form(QMainWindow):
    def __init__(self, splash):
        super(Form, self).__init__()
        self.resize(800, 500)
        self.splash = splash
        self.load_thread = QThread()
        self.load_worker = LoadDataWorker()
        self.load_worker.moveToThread(self.load_thread)
        self.load_thread.started.connect(self.load_worker.run)
        self.load_worker.message_signal.connect(self.set_message)
        self.load_worker.finished.connect(self.load_worker_finished)
        self.load_thread.start()
 
        while self.load_thread.isRunning():
            QtWidgets.qApp.processEvents() #Continuously refresh to ensure smooth animation
 
        self.load_thread.deleteLater()
 
    def load_worker_finished(self):
        self.load_thread.quit()
        self.load_thread.wait()
 
    def set_message(self, message):
        self.splash.showMessage(message, Qt.AlignLeft | Qt.AlignHCenter | Qt.AlignBottom, Qt.white)
 
 
if __name__ == '__main__':
    importsys
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    splash = MySplashScreen() # Set background image
    splash.setFont(QFont('Microsoft Yahei', 10)) # Set the font
    splash.show()
    app.processEvents() # Process the main process without lagging
    form = Form(splash)
    splash.finish(form) # Hide after the main interface is loaded
    splash.movie.stop() # Stop animation
    if NETWORK_STATUS == True:chatgui.main() # Judge a condition and enter the main interface
    splash.deleteLater()
    app.exec_()
    

Start interface effect

Code Overview:

  1. Import modules and libraries:

    import time from PyQt5 import QtWidgets from PyQt5.QtCore import Qt, QObject, QThread, pyqtSignal from PyQt5.QtGui import QFont, QMovie import requests import json

    In this part, we imported the modules and libraries required by the program, including PyQt5 for building the interface, time for controlling time, requests for making HTTP requests, and json for processing JSON data.

  2. Startup interface class MySplashScreen:

    class MySplashScreen(QSplashScreen): # ... (see the original text for detailed code)

    The MySplashScreen class inherits from QSplashScreen and is responsible for displaying the startup interface. Use QMovie to play a GIF animation, and prevent users from clicking on the startup interface by overriding the mousePressEvent method.

  3. Background data loading worker thread class LoadDataWorker:

    class LoadDataWorker(QObject): # ... (see the original text for detailed code)

    The LoadDataWorker class inherits from QObject and serves as a background worker thread, responsible for connecting to background services and sending corresponding messages. Define signals through pyqtSignal to send messages when work is completed and during work.

  4. Main interface class Form:

    class Form(QMainWindow): # ... (see the original text for detailed code)

    The Form class inherits from QMainWindow, in which a background worker thread is created, and the interface and the background worker thread are connected through the signal and slot mechanism to ensure that information during the startup process can be displayed in a timely manner. on the startup screen.

  5. Main program entrance:

    if __name__ == '__main__': # ... (see original text for detailed code)

    In the main program entry part, we create a QApplication object, display the startup interface, create the main interface, connect the background worker thread, and decide whether to enter the main interface based on the network status.

Among them, the MySplashScreen class is the implementation of the startup interface, using QMovie to play a GIF animation; the LoadDataWorker class is a working thread, responsible for connecting to background services and Send the corresponding message; the Form class is the main interface, responsible for starting the working thread, and continuously updating the messages on the startup interface during the startup process. The entire program is built using the PyQt5 library.