PyQt5 实现窗口大小变化自适应直线绘制
如果你希望绘制的直线能够随着窗口大小的变化而自适应,你可以使用 PyQt5 中的信号和槽机制来实现这一功能。以下是修改后的代码,可以实现可随窗口自适应的直线绘制:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt, QLine, QObject, pyqtSignal
class Communicate(QObject):
updateLine = pyqtSignal()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('绘制直线示例')
self.button1 = QPushButton('按钮1', self)
self.button1.setGeometry(50, 50, 100, 30)
self.button2 = QPushButton('按钮2', self)
self.button2.setGeometry(200, 50, 100, 30)
self.show()
self.communicate = Communicate()
self.communicate.updateLine.connect(self.updateLine)
def resizeEvent(self, event):
self.communicate.updateLine.emit()
def updateLine(self):
self.update()
def paintEvent(self, event):
painter = QPainter(self)
pen = QPen(Qt.black, 2, Qt.SolidLine)
painter.setPen(pen)
line = QLine(self.button1.x() + self.button1.width(), self.button1.y() + self.button1.height() // 2,
self.button2.x(), self.button2.y() + self.button2.height() // 2)
painter.drawLine(line)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
在这个修改后的代码中,我添加了一个名为'Communicate'的自定义 QObject 子类,并在其中定义了一个名为'updateLine'的信号。然后,在'MainWindow'类中,我创建了一个'Communicate'对象,并将其连接到窗口的'resizeEvent'事件。这意味着每当窗口大小发生变化时,'updateLine'信号将被发射。
在'updateLine'槽函数中,我们调用'update()'方法来触发窗口的重绘。这将导致'paintEvent'方法被调用,直线将根据新的按钮位置和大小进行绘制。
通过这种方式,直线将随着窗口大小的变化而自适应,保持连接两个按钮中心的位置。
原文地址: https://www.cveoy.top/t/topic/SX3 著作权归作者所有。请勿转载和采集!