不定时更新, 主要以伪代码形式
1.程序切换到前台时主窗口做一些工作
class mainWnd():
def __init__(self):
# 监听 focusChanged 信号
QApplication.instance().focusChanged.connect(self.handleFocusChanged)
def handleFocusChanged(self, old, new):
if old == None and new.window() == self:
self.refreshUI()
def refreshUI():
#做一些界面上的刷新之类的操作
2.给窗口加上最大化按钮
from PySide6.QtCore import Qt
self.setWindowFlags(self.windowFlags() & Qt.WindowType.WindowMaximizeButtonHint)
差异如下图所示:
3.控件在窗体大小变化时跟随变化
目前有两种方法 :
- 重写resizeEvent 方法在窗口变化时手动调整控件大小
def resizeEvent(self, arg__1: QResizeEvent) -> None:
#在这里处理
return super().resizeEvent(arg__1)
- 采用任意一种窗口布局,然后限制某些不需要变动的控件的尺寸,启用后这个小红标会消失
这两种方案我用起来都不太方便,暂时还没有找到其他方法替代
4.在某个控件上绘几何图形
我的需求是在图片上画网格,这里用到 QPainter,
需要注意的是
- 需要在哪个控件上画 就要重写这个控件的
paintEvent(QPaintEvent *)
方法,笔者之前重写的是window的这个方法 怎么改都不显示 super().paintEvent(event)
这里必须调用否则不会渲染图片paintEvent(QPaintEvent *
) 中代码执行的顺序 就是渲染的顺序 ,线条是要画在图片上的 所以要放在最后
from PySide6.QtWidgets import QLabel
from PySide6.QtGui import QPainter, QPixmap, QColor, QPen
class mapContainer(QLabel):
def __init__(self, *args):
super().__init__(*args)
self.gridSize = 64
def paintEvent(self, event):
super().paintEvent(event)
#灰色网格
painter = QPainter(self)
pen = QPen()
pen.setWidth(1)
pen.setColor(QColor(255,255,255,60))
painter.setPen(pen)
width = self.width()
height = self.height()
x = self.gridSize
while x < width:
painter.drawLine(x,0,x,height)
x += self.gridSize
y = self.gridSize
while y < height:
painter.drawLine(0,y,width,y)
y += self.gridSize
class window:
...
...
def addMap(self):
map = mapContainer(self)
pix = QPixmap( "map.png")
map.resize(pix.width(), pix.height())
map.setPixmap(pix)
map.setGridSize(64)
...
...
5.子线程进度显示
我现在有一个处理多文件的函数,如果在直接调用,主线程阻塞会阻塞很久,所以要放在子线程中处理,如果要在主线程中显示进度就要一些简单的跨线程交互,这里我们使用 queue
,Python中的queue模块提供了线程安全的队列实现,可以在多个线程之间安全地共享数据。要在多个线程之间使用队列,可以创建一个队列对象并将其传递给多个线程。线程可以使用put()方法将数据添加到队列中,使用get()方法从队列中获取数据。
import threading, time
import queue
class window:
...
...
def doSomething(self):
files = [a.txt,b.txt,c.txt ...]
#进度条重置
self.progressBar.setMaximum(len(files))
self.progressBar.setValue(0)
#用来判断进度
progressQueue = queue.Queue()
thread = threading.Thread(target=self.parseFiles,args=[files, progressQueue])
thread.start()
while thread.is_alive(): #轮询子线程状态
#见说明1
QApplication.processEvents()
#进度有更新,刷新进度条
if not progressQueue.empty():
pv = progressQueue.get()
self.progressBar.setValue(pv)
#轮询间隔
time.sleep(0.1)
def parseFiles(self, files, pQueue):
counter = 0
for file in files:
#处理这个文件
...
counter += 1
pQueue.put(counter)
#1 调用 QApplication.processEvents() 时,它会处理当前事件队列中的所有待处理事件,并且会让应用程序继续响应用户输入和更新界面。这个方法通常用于在长时间运行的任务中,以确保界面仍然能够响应用户操作。
6.设置按钮快捷键
使用QAbstractButton
的成员函数 setShortcut
,其子类都可以使用
button = QPushButton()
button.setShortcut('F5')
checkBox = QCheckBox()
checkBox.setShortcut('Alt+S')