PyQt5如何用QPainter在QScrollArea上画线?
一个QWidget界面,上面添加一个带滚动条的界面,如何用QPainter在该界面上画线?
class test(QWidget): def __init__(self):
super().__init__()
...
...
self.setUI()
def setUI(self):
self.setGeometry(250, 200, 1500, 750)
self.setWindowTitle('data structure visualization simulator')
self.topFiller = QWidget()
self.topFiller.setMinimumSize(1200, 2000)
self.scroll = QScrollArea()
self.scroll.setWidget(self.topFiller)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.scroll)
self.setLayout(self.vbox)
QPainter()中应该填什么对象?为什么在self上添加QPushButton可以在滚动条界面上显示,而画线就会被滚动条界面挡住?
def paintEvent(self, e): qp = QPainter(self)
pen = QPen()
pen.setWidth(1)
qp.setPen(pen)
qp.drawLine(15, 80, 1080, 120)
回答:
你应该为重画的控件写一个新类,继承自 QWidget,并重写 paintEvent 方法。
参考
# -*- coding: utf-8 -*-import sys
from PyQt5.QtWidgets import (
QApplication, QWidget, QVBoxLayout,
QScrollArea,
)
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtCore import Qt
class PaintWidget(QWidget):
def __init__(self):
super().__init__()
def paintEvent(self, event):
qp = QPainter()
qp.begin(self)
qp.setPen(QPen(QColor(0, 0, 255), 3, Qt.DotLine))
r = event.rect()
qp.drawLine(r.left(), r.top(), r.right(), r.bottom())
qp.end()
class TopWidget(QWidget):
def __init__(self):
super().__init__()
self.setUI()
self.show()
def setUI(self):
self.setGeometry(300, 300, 800, 400)
self.topFiller = PaintWidget()
self.topFiller.setMinimumSize(1200, 2000)
self.scroll = QScrollArea()
self.scroll.setWidget(self.topFiller)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.scroll)
self.setLayout(self.vbox)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Escape:
self.close()
if __name__ == '__main__':
app = QApplication([])
window = TopWidget()
sys.exit(app.exec_())
以上是 PyQt5如何用QPainter在QScrollArea上画线? 的全部内容, 来源链接: utcz.com/a/158109.html