from __future__ import annotations from PySide6.QtCore import QSize, Qt from PySide6.QtGui import QDragEnterEvent, QDropEvent, QIcon, QPixmap from PySide6.QtWidgets import ( QAbstractItemView, QDialog, QDialogButtonBox, QLabel, QListWidget, QListWidgetItem, QVBoxLayout, ) from pdfreaderlite.core.document import PdfDocument class PageGrid(QListWidget): def __init__(self) -> None: super().__init__() self.setViewMode(QListWidget.ViewMode.IconMode) self.setMovement(QListWidget.Movement.Snap) self.setResizeMode(QListWidget.ResizeMode.Adjust) self.setFlow(QListWidget.Flow.LeftToRight) self.setWrapping(True) self.setSpacing(12) self.setIconSize(QSize(140, 190)) self.setGridSize(QSize(178, 230)) self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove) self.setDefaultDropAction(Qt.DropAction.MoveAction) self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) def dropEvent(self, event: QDropEvent) -> None: super().dropEvent(event) self._renumber_items() def dragEnterEvent(self, event: QDragEnterEvent) -> None: event.acceptProposedAction() def _renumber_items(self) -> None: for row in range(self.count()): item = self.item(row) original_page = item.data(Qt.ItemDataRole.UserRole) + 1 item.setText(f"位置 {row + 1}\n原第 {original_page} 页") class PageManagerDialog(QDialog): def __init__(self, document: PdfDocument, parent=None) -> None: super().__init__(parent) self.document = document self.setWindowTitle("页面管理") self.resize(920, 680) self.grid = PageGrid() hint = QLabel("拖拽缩略图调整页面顺序,点击“应用”后写入当前 PDF。") hint.setWordWrap(True) buttons = QDialogButtonBox( QDialogButtonBox.StandardButton.Apply | QDialogButtonBox.StandardButton.Cancel ) buttons.button(QDialogButtonBox.StandardButton.Apply).setText("应用") buttons.rejected.connect(self.reject) buttons.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(self.accept) layout = QVBoxLayout(self) layout.addWidget(hint) layout.addWidget(self.grid, 1) layout.addWidget(buttons) self._load_pages() def page_order(self) -> list[int]: return [ self.grid.item(row).data(Qt.ItemDataRole.UserRole) for row in range(self.grid.count()) ] def _load_pages(self) -> None: for page_index in range(self.document.page_count): image = self.document.render_thumbnail(page_index, width=150) item = QListWidgetItem( QIcon(QPixmap.fromImage(image)), f"位置 {page_index + 1}\n原第 {page_index + 1} 页", ) item.setData(Qt.ItemDataRole.UserRole, page_index) item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) self.grid.addItem(item)