1
0
mirror of https://github.com/arsenetar/dupeguru.git synced 2026-01-22 06:37:17 +00:00

First pass code cleanup in qt/qtlib

This commit is contained in:
2021-08-24 00:12:23 -05:00
parent d576a7043c
commit f9085386a6
25 changed files with 195 additions and 233 deletions

View File

@@ -36,11 +36,11 @@ class AboutBox(QDialog):
def _setupUi(self):
self.setWindowTitle(tr("About {}").format(QCoreApplication.instance().applicationName()))
self.resize(400, 290)
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.setSizePolicy(sizePolicy)
size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.setSizePolicy(size_policy)
self.horizontalLayout = QHBoxLayout(self)
self.logoLabel = QLabel(self)
self.logoLabel.setPixmap(QPixmap(":/%s_big" % self.app.LOGO_NAME))

View File

@@ -22,7 +22,7 @@ from PyQt5.QtWidgets import (
from hscommon.trans import trget
from hscommon.desktop import open_url
from .util import horizontalSpacer
from .util import horizontal_spacer
tr = trget("qtlib")
@@ -34,10 +34,10 @@ class ErrorReportDialog(QDialog):
self._setupUi()
name = QCoreApplication.applicationName()
version = QCoreApplication.applicationVersion()
errorText = "Application Name: {}\nVersion: {}\n\n{}".format(name, version, error)
error_text = "Application Name: {}\nVersion: {}\n\n{}".format(name, version, error)
# Under windows, we end up with an error report without linesep if we don't mangle it
errorText = errorText.replace("\n", os.linesep)
self.errorTextEdit.setPlainText(errorText)
error_text = error_text.replace("\n", os.linesep)
self.errorTextEdit.setPlainText(error_text)
self.github_url = github_url
self.sendButton.clicked.connect(self.goToGithub)
@@ -68,7 +68,7 @@ class ErrorReportDialog(QDialog):
self.label2.setWordWrap(True)
self.verticalLayout.addWidget(self.label2)
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.addItem(horizontalSpacer())
self.horizontalLayout.addItem(horizontal_spacer())
self.dontSendButton = QPushButton(self)
self.dontSendButton.setText(tr("Close"))
self.dontSendButton.setMinimumSize(QSize(110, 0))

View File

@@ -8,7 +8,7 @@
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QRadioButton
from .util import horizontalSpacer
from .util import horizontal_spacer
class RadioBox(QWidget):
@@ -21,7 +21,7 @@ class RadioBox(QWidget):
self._buttons = []
self._labels = items
self._selected_index = 0
self._spacer = horizontalSpacer() if not spread else None
self._spacer = horizontal_spacer() if not spread else None
self._layout = QHBoxLayout(self)
self._update_buttons()

View File

@@ -20,12 +20,12 @@ MenuEntry = namedtuple("MenuEntry", "menu fixedItemCount")
class Recent(QObject):
def __init__(self, app, prefName, maxItemCount=10, **kwargs):
def __init__(self, app, pref_name, max_item_count=10, **kwargs):
super().__init__(**kwargs)
self._app = app
self._menuEntries = []
self._prefName = prefName
self._maxItemCount = maxItemCount
self._prefName = pref_name
self._maxItemCount = max_item_count
self._items = []
self._loadFromPrefs()
@@ -41,9 +41,9 @@ class Recent(QObject):
def _insertItem(self, item):
self._items = dedupe([item] + self._items)[: self._maxItemCount]
def _refreshMenu(self, menuEntry):
menu, fixedItemCount = menuEntry
for action in menu.actions()[fixedItemCount:]:
def _refreshMenu(self, menu_entry):
menu, fixed_item_count = menu_entry
for action in menu.actions()[fixed_item_count:]:
menu.removeAction(action)
for item in self._items:
action = QAction(item, menu)
@@ -56,17 +56,17 @@ class Recent(QObject):
menu.addAction(action)
def _refreshAllMenus(self):
for menuEntry in self._menuEntries:
self._refreshMenu(menuEntry)
for menu_entry in self._menuEntries:
self._refreshMenu(menu_entry)
def _saveToPrefs(self):
setattr(self._app.prefs, self._prefName, self._items)
# --- Public
def addMenu(self, menu):
menuEntry = MenuEntry(menu, len(menu.actions()))
self._menuEntries.append(menuEntry)
self._refreshMenu(menuEntry)
menu_entry = MenuEntry(menu, len(menu.actions()))
self._menuEntries.append(menu_entry)
self._refreshMenu(menu_entry)
def clear(self):
self._items = []

View File

@@ -36,9 +36,9 @@ class ClearableEdit(QLineEdit):
self._is_clearable = is_clearable
if is_clearable:
self._clearButton = LineEditButton(self)
frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
paddingRight = self._clearButton.sizeHint().width() + frameWidth + 1
stylesheet = "QLineEdit {{ padding-right:{0}px; }}".format(paddingRight)
frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
padding_right = self._clearButton.sizeHint().width() + frame_width + 1
stylesheet = "QLineEdit {{ padding-right:{0}px; }}".format(padding_right)
self.setStyleSheet(stylesheet)
self._updateClearButton()
@@ -58,12 +58,12 @@ class ClearableEdit(QLineEdit):
# --- QLineEdit overrides
def resizeEvent(self, event):
if self._is_clearable:
frameWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth)
rect = self.rect()
rightHint = self._clearButton.sizeHint()
rightX = rect.right() - frameWidth - rightHint.width()
rightY = (rect.bottom() - rightHint.height()) // 2
self._clearButton.move(rightX, rightY)
right_hint = self._clearButton.sizeHint()
right_x = rect.right() - frame_width - right_hint.width()
right_y = (rect.bottom() - right_hint.height()) // 2
self._clearButton.move(right_x, right_y)
# --- Event Handlers
def _textChanged(self, text):
@@ -102,14 +102,14 @@ class SearchEdit(ClearableEdit):
if not bool(self.text()) and self.inactiveText and not self.hasFocus():
panel = QStyleOptionFrame()
self.initStyleOption(panel)
textRect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
leftMargin = 2
rightMargin = self._clearButton.iconSize().width()
textRect.adjust(leftMargin, 0, -rightMargin, 0)
text_rect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
left_margin = 2
right_margin = self._clearButton.iconSize().width()
text_rect.adjust(left_margin, 0, -right_margin, 0)
painter = QPainter(self)
disabledColor = self.palette().brush(QPalette.Disabled, QPalette.Text).color()
painter.setPen(disabledColor)
painter.drawText(textRect, Qt.AlignLeft | Qt.AlignVCenter, self.inactiveText)
disabled_color = self.palette().brush(QPalette.Disabled, QPalette.Text).color()
painter.setPen(disabled_color)
painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, self.inactiveText)
# --- Event Handlers
def _returnPressed(self):

View File

@@ -80,19 +80,19 @@ class ListviewModel(SelectableList):
# --- Override
def _updateSelection(self):
newIndexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()]
if newIndexes != self.model.selected_indexes:
self.model.select(newIndexes)
new_indexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()]
if new_indexes != self.model.selected_indexes:
self.model.select(new_indexes)
def _restoreSelection(self):
newSelection = QItemSelection()
new_selection = QItemSelection()
for index in self.model.selected_indexes:
newSelection.select(self.createIndex(index, 0), self.createIndex(index, 0))
self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect)
if len(newSelection.indexes()):
currentIndex = newSelection.indexes()[0]
self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current)
self.view.scrollTo(currentIndex)
new_selection.select(self.createIndex(index, 0), self.createIndex(index, 0))
self.view.selectionModel().select(new_selection, QItemSelectionModel.ClearAndSelect)
if len(new_selection.indexes()):
current_index = new_selection.indexes()[0]
self.view.selectionModel().setCurrentIndex(current_index, QItemSelectionModel.Current)
self.view.scrollTo(current_index)
# --- Events
def selectionChanged(self, index):

View File

@@ -38,21 +38,21 @@ class Table(QAbstractTableModel):
# an _updateViewSelection() call will normally result in an _updateModelSelection() call.
# to avoid infinite loops, we check that the selection will actually change before calling
# model.select()
newIndexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()]
if newIndexes != self.model.selected_indexes:
self.model.select(newIndexes)
new_indexes = [modelIndex.row() for modelIndex in self.view.selectionModel().selectedRows()]
if new_indexes != self.model.selected_indexes:
self.model.select(new_indexes)
def _updateViewSelection(self):
# Takes the selection on the model's side and update the view with it.
newSelection = QItemSelection()
columnCount = self.columnCount(QModelIndex())
new_selection = QItemSelection()
column_count = self.columnCount(QModelIndex())
for index in self.model.selected_indexes:
newSelection.select(self.createIndex(index, 0), self.createIndex(index, columnCount - 1))
self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect)
if len(newSelection.indexes()):
currentIndex = newSelection.indexes()[0]
self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current)
self.view.scrollTo(currentIndex)
new_selection.select(self.createIndex(index, 0), self.createIndex(index, column_count - 1))
self.view.selectionModel().select(new_selection, QItemSelectionModel.ClearAndSelect)
if len(new_selection.indexes()):
current_index = new_selection.indexes()[0]
self.view.selectionModel().setCurrentIndex(current_index, QItemSelectionModel.Current)
self.view.scrollTo(current_index)
# --- Data Model methods
# Virtual

View File

@@ -26,27 +26,27 @@ from PyQt5.QtWidgets import (
)
def moveToScreenCenter(widget):
def move_to_screen_center(widget):
frame = widget.frameGeometry()
frame.moveCenter(QDesktopWidget().availableGeometry().center())
widget.move(frame.topLeft())
def verticalSpacer(size=None):
def vertical_spacer(size=None):
if size:
return QSpacerItem(1, size, QSizePolicy.Fixed, QSizePolicy.Fixed)
else:
return QSpacerItem(1, 1, QSizePolicy.Fixed, QSizePolicy.MinimumExpanding)
def horizontalSpacer(size=None):
def horizontal_spacer(size=None):
if size:
return QSpacerItem(size, 1, QSizePolicy.Fixed, QSizePolicy.Fixed)
else:
return QSpacerItem(1, 1, QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
def horizontalWrap(widgets):
def horizontal_wrap(widgets):
"""Wrap all widgets in `widgets` in a horizontal layout.
If, instead of placing a widget in your list, you place an int or None, an horizontal spacer
@@ -55,14 +55,14 @@ def horizontalWrap(widgets):
layout = QHBoxLayout()
for widget in widgets:
if widget is None or isinstance(widget, int):
layout.addItem(horizontalSpacer(size=widget))
layout.addItem(horizontal_spacer(size=widget))
else:
layout.addWidget(widget)
return layout
def createActions(actions, target):
# actions = [(name, shortcut, icon, desc, func)]
def create_actions(actions, target):
# actions are list of (name, shortcut, icon, desc, func)
for name, shortcut, icon, desc, func in actions:
action = QAction(target)
if icon:
@@ -74,7 +74,7 @@ def createActions(actions, target):
setattr(target, name, action)
def setAccelKeys(menu):
def set_accel_keys(menu):
actions = menu.actions()
titles = [a.text() for a in actions]
available_characters = {c.lower() for s in titles for c in s if c.isalpha()}
@@ -89,7 +89,7 @@ def setAccelKeys(menu):
action.setText(newtext)
def getAppData(portable=False):
def get_appdata(portable=False):
if portable:
return op.join(executable_folder(), "data")
else:
@@ -102,11 +102,11 @@ class SysWrapper(io.IOBase):
logging.warning(s)
def setupQtLogging(level=logging.WARNING, log_to_stdout=False):
def setup_qt_logging(level=logging.WARNING, log_to_stdout=False):
# Under Qt, we log in "debug.log" in appdata. Moreover, when under cx_freeze, we have a
# problem because sys.stdout and sys.stderr are None, so we need to replace them with a
# wrapper that logs with the logging module.
appdata = getAppData()
appdata = get_appdata()
if not op.exists(appdata):
os.makedirs(appdata)
# Setup logging
@@ -123,7 +123,7 @@ def setupQtLogging(level=logging.WARNING, log_to_stdout=False):
sys.stdout = SysWrapper()
def escapeamp(s):
def escape_amp(s):
# Returns `s` with escaped ampersand (& --> &&). QAction text needs to have & escaped because
# that character is used to define "accel keys".
return s.replace("&", "&&")