"""Shared scroll areas and read-only tables for Qt workspaces.""" from __future__ import annotations try: from PySide6.QtCore import Qt from PySide6.QtGui import QAction, QKeySequence from PySide6.QtWidgets import ( QAbstractItemView, QApplication, QHeaderView, QScrollArea, QTableWidget, QVBoxLayout, QWidget, ) except ImportError: from PySide2.QtCore import Qt from PySide2.QtGui import QKeySequence from PySide2.QtWidgets import ( QAbstractItemView, QAction, QApplication, QHeaderView, QScrollArea, QTableWidget, QVBoxLayout, QWidget, ) def make_scrollable(content: QWidget) -> QScrollArea: """Wrap a widget in a resizable, frameless scroll area.""" scroll = QScrollArea() scroll.setWidgetResizable(True) scroll.setFrameShape(QScrollArea.NoFrame) scroll.setWidget(content) return scroll def make_settings_page(settings: QWidget) -> QScrollArea: """Keep settings at the top of a scrollable page.""" page = QWidget() layout = QVBoxLayout(page) layout.setContentsMargins(12, 12, 12, 12) layout.addWidget(settings) layout.addStretch(1) return make_scrollable(page) def copy_table_selection(table: QTableWidget) -> str: """Copy the selected cells as tab-separated rows.""" indexes = sorted(table.selectedIndexes(), key=lambda item: (item.row(), item.column())) if not indexes: return "" rows: dict[int, list[str]] = {} for index in indexes: value = index.data() rows.setdefault(index.row(), []).append("" if value is None else str(value)) text = "\n".join("\t".join(values) for values in rows.values()) QApplication.clipboard().setText(text) return text def enable_table_copy(table: QTableWidget) -> None: """Add Ctrl+C and a copy action to the table.""" table.setSelectionMode(QTableWidget.ExtendedSelection) action = QAction("Копировать выбранное", table) action.setShortcut(QKeySequence.Copy) action.setShortcutContext(Qt.WidgetShortcut) action.triggered.connect(lambda: copy_table_selection(table)) table.addAction(action) table.setContextMenuPolicy(Qt.ActionsContextMenu) table.setToolTip( "Выделите одну или несколько строк и нажмите Ctrl+C; " "копирование также доступно по правой кнопке мыши." ) def make_monitor_table(headers, *, font, widths=()) -> QTableWidget: """Create a read-only monitor table with row selection and clipboard support.""" table = QTableWidget(0, len(headers)) table.setHorizontalHeaderLabels(headers) table.setEditTriggers(QAbstractItemView.NoEditTriggers) table.setSelectionBehavior(QAbstractItemView.SelectRows) enable_table_copy(table) table.verticalHeader().setVisible(False) table.setFont(font) for column, width in enumerate(widths): table.setColumnWidth(column, width) if headers: table.horizontalHeader().setSectionResizeMode(len(headers) - 1, QHeaderView.Stretch) return table