我正在 QPdfView 中显示 pdf 文档,并且需要在几页上的某些区域上绘制覆盖层。
我已经设法绘制了覆盖层,但我需要一些帮助来调整滚动时其位置的调整方式。
代码如下:
from PySide6.QtCore import QRectF
from PySide6.QtGui import QPainter, QColor
from PySide6.QtPdfWidgets import QPdfView
from PySide6.QtCore import Qt
from PySide6.QtPdf import QPdfDocument
class CustomPdfView(QPdfView):
def __init__(self, parent=None):
super().__init__(parent)
# Placeholder areas
self.highlights: dict[int, list[QRectF]] = {
i : [QRectF(150.0, 150.0, 300.0, 300.0)] for i in range(200)
}
def paintEvent(self, event):
super().paintEvent(event)
if self.document().status() == QPdfDocument.Status.Ready:
current_page_number = self.pageNavigator().currentPage()
if current_page_number in self.highlights.keys():
painter = QPainter(self.viewport())
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setBrush(QColor(255, 255, 0, 100))
painter.setPen(Qt.PenStyle.NoPen)
total_pages = self.document().pageCount()
current_page_size = self.document().pagePointSize(current_page_number)
viewport_size = self.viewport().size()
scroll_bar = self.verticalScrollBar()
max_scroll = scroll_bar.maximum()
scroll_per_page = max_scroll / total_pages
scroll_calculated = scroll_per_page * current_page_number
for rect in self.highlights[current_page_number]:
h_diff = scroll_bar.value() - scroll_calculated
scaled_rect = QRectF(
(rect.x() / current_page_size.width()) * viewport_size.width(),
rect.y() - h_diff,
(rect.width() / current_page_size.width()) * viewport_size.width(),
rect.height()
)
painter.drawRect(scaled_rect)
painter.end()
在最好的情况下,我想知道当前页面在视口中呈现了多少像素,因此 h_diff 变为 page_height - 可见像素