写在前面:
考虑已经陆陆续续在平台写了几篇PyQt5开发的小工具,后续还会继续发布新的新工具,这些工具都基于一个基础结构往上构建,这个基础结构是本人自己开发的习惯,在这里把工具的基础结构代码抽取出来,后续要开发新的工具直接复制结构代码,然后就可以直接开发主体。
界面:
1 进度条,基础结构里会有一个线程,耗时的业务在线程中执行
2 主体界面, 在主体位置放置业务相关控件
代码:
import sys
from threading import Thread
from typing import Dict,Any
from PyQt5 import QtCore,QtWidgets,QtGui
from PyQt5.QtCore import Qt
import pyqtgraph as pg
pg.setConfigOption('background','w')
pg.setConfigOption('foreground','k')
class BaseMainWidget(QtWidgets.QWidget):
signal_excute = QtCore.pyqtSignal(object)
def __init__(self):
super().__init__()
self.thread_caculate: Thread = None
self.init_data()
self.init_ui()
self.register_event()
self.progress_init()
pass
def init_data(self):
pass
def init_ui(self):
self.setWindowTitle('PyQt5开发工具结构基础')
self.setMinimumWidth(600)
self.setMinimumHeight(400)
self.caculate_progress = QtWidgets.QProgressBar()
self.caculate_status_label = QtWidgets.QLabel()
layout_progress = QtWidgets.QHBoxLayout()
layout_progress.addWidget(self.caculate_progress)
layout_progress.addWidget(self.caculate_status_label)
temp_label = QtWidgets.QLabel('PyQt5开发工具结构基础\n这里放置业务内容')
temp_label.setAlignment(Qt.AlignCenter)
temp_label.setStyleSheet('QLabel{font-size:32px;font-weight:bold;}')
layout_one = QtWidgets.QVBoxLayout()
layout_one.addStretch(1)
layout_one.addWidget(temp_label)
layout_one.addStretch(1)
layout = QtWidgets.QVBoxLayout()
layout.addLayout(layout_progress)
layout.addLayout(layout_one)
self.setLayout(layout)
pass
def register_event(self):
self.signal_excute.connect(self.process_excute_event)
pass
def process_excute_event(self,data:Dict):
pass
def start_caculate_thread(self,mark_str:str,data:Dict[str,Any]):
if self.thread_caculate:
QtWidgets.QMessageBox.information(
self,
'提示',
'线程正在执行任务,请稍后。。。',
QtWidgets.QMessageBox.Yes
)
return
self.thread_caculate = Thread(
target=self.running_caculate_thread,
args=(
mark_str, data,
)
)
self.thread_caculate.start()
self.progress_busy()
pass
def running_caculate_thread(self,mark_str:str,data:Dict[str,Any]):
pass
def progress_init(self) -> None:
self.caculate_progress.setValue(0)
self.caculate_status_label.setText('无任务')
def progress_busy(self) -> None:
self.caculate_progress.setRange(0, 0)
self.caculate_status_label.setText('正在执行')
def progress_finished(self) -> None:
self.caculate_progress.setRange(0, 100)
self.caculate_progress.setValue(100)
self.caculate_status_label.setText('执行完毕')
pass
def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
self.close()
pass
if __name__ == '__main__':
QtCore.QCoreApplication.setAttribute(QtCore.Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
app = QtWidgets.QApplication(sys.argv)
main_window = BaseMainWidget()
main_window.show()
app.exec()
pass