我正在尝试开发一个包含许多我的自定义小部件的程序。在我的小部件中,我有一个十字准线鼠标指针,当我在其中一个小部件中移动它时,它们都必须感应到它,并且十字准线必须对每个小部件做出反应。我在 paintEnent 函数的末尾有一个 self.update() 。
如何强制我的应用程序上的其他小部件对其做出反应?
paintEvent 不是这样的简单代码,当我在这部分添加每个函数时,它会占用非常高的 CPU 使用率。我该如何管理它?
import sys from PyQt5.QtWidgets import QApplication, QDialog, QListWidget, QComboBox, QVBoxLayout, QPushButton, QLabel, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QSizePolicy from PyQt5.QtCore import Qt, QSize, QRect from PyQt5.QtGui import QPalette, QColor, QPen, QPixmap, QPainter, QBrush class Boom(QWidget): xPos=-1.0 def __init__(self,bgColor,xSpace=1,ySpace=1): super().__init__() self.bgColor=bgColor self.x = -1 self.y = -1 self.setSizePolicy(QSizePolicy.MinimumExpanding,QSizePolicy.MinimumExpanding) self.setMouseTracking(True) layout = QVBoxLayout() self.setLayout(layout) def mouseMoveEvent(self, event): global xPos self.x = event.x() self.y = event.y() xPos=self.x/self.width() self.update() def paintEvent(self, e): painter = QPainter(self) font = painter.font() font.setFamily('Times') font.setPointSize(8) painter.setFont(font) brush = QBrush() brush.setColor(QColor(self.bgColor)) brush.setStyle(Qt.SolidPattern) pen = QPen() pen.setWidth(1) pen.setColor(QColor('black')) painter.setPen(pen) rect = QRect(0, 0, painter.device().width(), painter.device().height()) painter.fillRect(rect, brush) pen.setColor(QColor('blue')) painter.setPen(pen) painter.drawLine(self.x, 0, self.x,painter.device().height()) #V painter.drawLine(0, self.y, painter.device().width(),self.y) #H self.update() painter.end() class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Graph") MainPanelLayout = QHBoxLayout() MainPanelLayout.setContentsMargins(1,1,1,1) MainPanelLayout.setSpacing(1) B1=Boom('pink',0) B2=Boom('gray',1) MainPanelLayout.addWidget(B1) MainPanelLayout.addWidget(B2) widget = QWidget() widget.setLayout(MainPanelLayout) self.setCentralWidget(widget) if __name__ == "__main__": app = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() # mainWindow.showMaximized() app.exec_()