首页 > 解决方案 > PyQt5 并发主循环

问题描述

尝试在线程中运行 pyqt5(将运行多个,因此需要线程以便非阻塞)。此示例应在 50,50 处启动 25x25 无头窗口,并在屏幕左侧或右侧更改背景。可以让它在没有线程的情况下工作,但我需要线程功能

编辑:

import sys
import threading
import pynput
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget


class Overlay(threading.Thread):
    mouse = pynput.mouse.Controller
    tr, tg, tb = None, None, None
    fr, fg, fb = None, None, None
    xloc, yloc, width, height = None, None, None, None

    def __init__(self, x, y, w=25, h=25, r=255, g=255, b=255, rr=0, gg=0, bb=0):
        threading.Thread.__init__(self)
        self.App = QApplication(sys.argv)
        self.window = QMainWindow()
        self.mainloop = QTimer(self.window)
        self.tr, self.tg, self.tb = r, g, b
        self.fr, self.fg, self.fb = rr, gg, bb
        self.xloc, self.yloc, self.width, self.height = x, y, w, h
        self.window.setWindowFlag(Qt.FramelessWindowHint)
        self.window.setGeometry(self.xloc, self.yloc, self.width, self.height)
        self.mainloop.timeout.connect(self.mainLoop)
        self.mainloop.start()
        self.window.show()

    def run(self):
        self.App.exec()

    def mainLoop(self):
        if self.mouse.position[0] > 960:
            self.setStyleSheet(f"background-color: red;")
        else:
            self.setStyleSheet(f"background-color: blue;")


thread = Overlay(50, 50)
thread.start()
print("Non blocking")
while True:
    print("running")

标签: pythonpyqt5

解决方案


推荐阅读