working on stopping headers from leaving viewport on resize

This commit is contained in:
tsi-billypom 2024-09-17 16:52:36 -04:00
parent cb40fd0a57
commit 240f449f0a
5 changed files with 46 additions and 33 deletions

View File

@ -13,16 +13,17 @@ from PyQt5.QtWidgets import (
QAction, QAction,
QHeaderView, QHeaderView,
QMenu, QMenu,
QSizePolicy,
QTableView, QTableView,
QShortcut, QShortcut,
QMessageBox, QMessageBox,
QAbstractItemView, QAbstractItemView,
) )
from PyQt5.QtCore import ( from PyQt5.QtCore import (
Qt,
QAbstractItemModel, QAbstractItemModel,
QModelIndex, QModelIndex,
QThreadPool, QThreadPool,
Qt,
pyqtSignal, pyqtSignal,
QTimer, QTimer,
) )
@ -95,8 +96,8 @@ class MusicTable(QTableView):
None, None,
] ]
# Header stuff... # Header stuff...
header = ResizableHeaderView(Qt.Horizontal, self) # header = ResizableHeaderView(Qt.Horizontal, self)
self.setHorizontalHeader(header) # self.setHorizontalHeader(header)
# hide the id column # hide the id column
self.hideColumn(0) self.hideColumn(0)
# db names of headers # db names of headers
@ -105,21 +106,42 @@ class MusicTable(QTableView):
self.songChanged = None self.songChanged = None
self.selected_song_filepath = "" self.selected_song_filepath = ""
self.current_song_filepath = "" self.current_song_filepath = ""
# self.tableView.resizeColumnsToContents() table_view_column_widths = str(self.config["table"]["column_widths"]).split(",")
for i in range(self.model.columnCount() - 1):
self.setColumnWidth(i, int(table_view_column_widths[i]))
self.horizontalHeader().setStretchLastSection(True)
self.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.horizontalHeader().setCascadingSectionResizes(True)
# CONNECTIONS
self.clicked.connect(self.set_selected_song_filepath) self.clicked.connect(self.set_selected_song_filepath)
# doubleClicked is a built in event for QTableView - we listen for this event and run set_current_song_filepath
self.doubleClicked.connect(self.set_current_song_filepath) self.doubleClicked.connect(self.set_current_song_filepath)
self.enterKey.connect(self.set_current_song_filepath) self.enterKey.connect(self.set_current_song_filepath)
self.deleteKey.connect(self.delete_songs) self.deleteKey.connect(self.delete_songs)
self.model.dataChanged.connect(self.on_cell_data_changed) # editing cells self.model.dataChanged.connect(self.on_cell_data_changed) # editing cells
self.model.layoutChanged.connect(self.restore_scroll_position) self.model.layoutChanged.connect(self.restore_scroll_position)
self.horizontalHeader().sectionResized.connect(self.header_was_resized)
# Final actions
self.load_music_table() self.load_music_table()
self.setup_keyboard_shortcuts() self.setup_keyboard_shortcuts()
def resizeEvent(self, e: typing.Optional[QResizeEvent]) -> None: def resizeEvent(self, e: typing.Optional[QResizeEvent]) -> None:
print(f"QTableView size: {self.size().width()}")
if e is None: if e is None:
raise Exception raise Exception
super().resizeEvent(e) super().resizeEvent(e)
self.setMaximumSize(self.size().width(), self.size().height())
def header_was_resized(self, logicalIndex, oldSize, newSize):
# super().sectionResized(logicalIndex, oldSize, newSize)
self.adjust_section_sizes()
def adjust_section_sizes(self):
column_count = self.model.columnCount()
total_width = 0
for i in range(self.model.columnCount()):
total_width += self.columnWidth(i)
print(f"total_width = {total_width}")
def contextMenuEvent(self, a0): def contextMenuEvent(self, a0):
"""Right-click context menu for rows in Music Table""" """Right-click context menu for rows in Music Table"""

View File

@ -8,19 +8,14 @@ class ResizableHeaderView(QHeaderView):
super().__init__(orientation, parent) super().__init__(orientation, parent)
self.config = configparser.ConfigParser() self.config = configparser.ConfigParser()
self.config.read("config.ini") self.config.read("config.ini")
self.parent = parent
# FIXME: last column needs to not leave the screen when other columns become big... # FIXME: last column needs to not leave the screen when other columns become big...
# howwww # howwww
table_view_column_widths = str(self.config["table"]["column_widths"]).split(",") table_view_column_widths = str(self.config["table"]["column_widths"]).split(",")
for i in range(parent.model.columnCount() - 1): for i in range(parent.model.columnCount() - 1):
self.setColumnWidth(i, int(table_view_column_widths[i])) self.setColumnWidth(i, int(table_view_column_widths[i]))
self.setSectionsMovable(True)
self.setSectionResizeMode(QHeaderView.Interactive)
self.setStretchLastSection(True) self.setStretchLastSection(True)
self.min_section_size = 50 self.setSectionResizeMode(QHeaderView.Interactive)
self.default_column_proportions = [1, 1, 1, 1, 1, 1, 1, 1]
def set_default_column_proportions(self, proportions):
self.default_column_proportions = proportions
def resizeEvent(self, e): def resizeEvent(self, e):
super().resizeEvent(e) super().resizeEvent(e)
@ -31,25 +26,12 @@ class ResizableHeaderView(QHeaderView):
self.adjust_section_sizes() self.adjust_section_sizes()
def adjust_section_sizes(self): def adjust_section_sizes(self):
total_width = self.width()
column_count = self.count() column_count = self.count()
total_width = 0
for i in range(self.parent.model.columnCount()):
total_width += self.parent.model.columnWidth(i)
print(f"total_width = {total_width}")
if not self.default_column_proportions: if not self.default_column_proportions:
self.default_column_proportions = [1] * column_count self.default_column_proportions = [1] * column_count
# Calculate the total proportion
total_proportion = sum(self.default_column_proportions)
# Calculate sizes based on proportions
sizes = [
max(self.min_section_size, int(total_width * prop / total_proportion))
for prop in self.default_column_proportions
]
# Adjust sizes to fit exactly
extra = total_width - sum(sizes)
for i in range(abs(extra)):
sizes[i % column_count] += 1 if extra > 0 else -1
# Apply sizes
for i in range(column_count):
self.resizeSection(i, sizes[i])

View File

@ -4,7 +4,7 @@ import sys
import logging import logging
from subprocess import run from subprocess import run
import qdarktheme import qdarktheme
import typing
from pyqtgraph import mkBrush from pyqtgraph import mkBrush
from mutagen.id3 import ID3 from mutagen.id3 import ID3
from mutagen.id3._frames import APIC from mutagen.id3._frames import APIC
@ -34,7 +34,7 @@ from PyQt5.QtCore import (
QRunnable, QRunnable,
) )
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent, QAudioProbe from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent, QAudioProbe
from PyQt5.QtGui import QCloseEvent, QPixmap from PyQt5.QtGui import QCloseEvent, QPixmap, QResizeEvent
from utils import ( from utils import (
scan_for_music, scan_for_music,
delete_and_create_library_database, delete_and_create_library_database,
@ -255,6 +255,11 @@ class ApplicationWindow(QMainWindow, Ui_MainWindow):
"""Returns the threadpool instance""" """Returns the threadpool instance"""
return self.threadpool return self.threadpool
def resizeEvent(self, a0: typing.Optional[QResizeEvent]) -> None:
"""Do something when the window resizes"""
if a0 is not None:
return super().resizeEvent(a0)
def closeEvent(self, a0: QCloseEvent | None) -> None: def closeEvent(self, a0: QCloseEvent | None) -> None:
"""Save settings when closing the application""" """Save settings when closing the application"""
# MusicTable/tableView column widths # MusicTable/tableView column widths

1
ui.py
View File

@ -100,6 +100,7 @@ class Ui_MainWindow(object):
self.hLayoutHead.setStretch(2, 6) self.hLayoutHead.setStretch(2, 6)
self.verticalLayout.addLayout(self.hLayoutHead) self.verticalLayout.addLayout(self.hLayoutHead)
self.hLayoutMusicTable = QtWidgets.QHBoxLayout() self.hLayoutMusicTable = QtWidgets.QHBoxLayout()
self.hLayoutMusicTable.setSizeConstraint(QtWidgets.QLayout.SetMaximumSize)
self.hLayoutMusicTable.setContentsMargins(0, -1, 0, -1) self.hLayoutMusicTable.setContentsMargins(0, -1, 0, -1)
self.hLayoutMusicTable.setObjectName("hLayoutMusicTable") self.hLayoutMusicTable.setObjectName("hLayoutMusicTable")
self.playlistTreeView = PlaylistsPane(self.centralwidget) self.playlistTreeView = PlaylistsPane(self.centralwidget)

3
ui.ui
View File

@ -166,6 +166,9 @@
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="hLayoutMusicTable" stretch="2,10"> <layout class="QHBoxLayout" name="hLayoutMusicTable" stretch="2,10">
<property name="sizeConstraint">
<enum>QLayout::SetMaximumSize</enum>
</property>
<property name="leftMargin"> <property name="leftMargin">
<number>0</number> <number>0</number>
</property> </property>