Skip to content

Commit

Permalink
refactor: Fix Qt flags (#1041)
Browse files Browse the repository at this point in the history
Instead of using global `Qt` or Widget namespaces for enum selection
point, enum directly.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced the About dialog to support parent window association for
better modal behavior.
- Advanced tabs, mask control, and advanced window classes now accept a
parent argument for improved widget hierarchy management.
- Profile selection and color map creation processes have been refined
with updated initialization parameters.
- Custom load and save dialog conditions and method calls have been
updated for consistency with the latest dialog standards.

- **Bug Fixes**
- Corrected the context menu policy settings for various GUI components
to align with updated Qt enumerations.
- Adjusted file dialog acceptance checks to use the revised dialog code
enumeration.
- Resolved issues with incorrect enum usage in searchable combo boxes
and list widgets, ensuring proper item filtering and selection behavior.

- **Documentation**
- Updated comments and docstrings across multiple modules for better
clarity and understanding of the codebase.

- **Refactor**
- Standardized the use of enum values across the application, replacing
direct value usage with fully qualified enum names for better code
maintainability and readability.

- **Style**
- Minor stylistic changes in comments and method calls to adhere to the
updated coding standards and conventions.

Please note that these changes are aimed at improving the user
experience and ensuring compatibility with the latest standards and
practices in application development.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
Czaki authored Dec 8, 2023
1 parent fb4a266 commit 107c615
Show file tree
Hide file tree
Showing 20 changed files with 74 additions and 70 deletions.
8 changes: 4 additions & 4 deletions package/PartSeg/common_gui/about_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@


class AboutDialog(QDialog):
def __init__(self):
super().__init__()
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle("About PartSeg")
text = (
f"<strong>PartSeg</strong> ({PartSeg.__version__})<br>"
Expand Down Expand Up @@ -46,8 +46,8 @@ def __init__(self):
self.cite_as.setMarkdown(cite_as_text)
ok_but = QPushButton("Ok")
ok_but.clicked.connect(self.accept)
text_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
layout = QGridLayout()
text_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
layout = QGridLayout(self)
layout.addWidget(text_label, 0, 0, 1, 3)
layout.addWidget(self.change_log, 1, 0, 1, 3)
layout.addWidget(QLabel("Cite as:"), 2, 0, 1, 3)
Expand Down
24 changes: 12 additions & 12 deletions package/PartSeg/common_gui/advanced_tabs.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
This module contains base for advanced window for PartSeg.
In this moment controlling colormaps tabs and developer PartSegCore
This module contains base for the advanced window for PartSeg.
At this moment controlling colormaps tabs and developer PartSegCore
"""
import importlib
import sys
Expand Down Expand Up @@ -41,22 +41,22 @@ class DevelopTab(QWidget):
"""
Widget for developer utilities. Currently only contains button for reload algorithms and
To enable it run program with `--develop` flag.
To enable it run program with a `--develop` flag.
If you would like to use it for developing your own algorithm and modify same of ParsSeg class
please protect this part of code with something like:
If you would like to use it for developing your own algorithm and modify some of the PartSeg class.
Please protect this part of code with something like:
>>> if tifffile.tifffile.TiffPage.__module__ != "PartSegImage.image_reader":
This is taken from :py:mod:`PartSegImage.image_reader`
"""

def __init__(self):
super().__init__()
def __init__(self, parent=None):
super().__init__(parent=parent)

# noinspection PyArgumentList
self.reload_btn = QPushButton("Reload algorithms", clicked=self.reload_algorithm_action)
layout = QGridLayout()
layout = QGridLayout(self)
layout.addWidget(self.reload_btn, 0, 0)
layout.setColumnStretch(1, 1)
layout.setRowStretch(1, 1)
Expand All @@ -83,15 +83,15 @@ def reload_algorithm_action(self):


class MaskControl(QWidget):
def __init__(self, settings: ViewSettings):
super().__init__()
def __init__(self, settings: ViewSettings, parent=None):
super().__init__(parent=parent)
self.settings = settings
self.color_picker = QColorDialog()
self.color_picker.setWindowFlag(Qt.WindowType.Widget)
self.color_picker.setOptions(
QColorDialog.ColorDialogOption.DontUseNativeDialog | QColorDialog.ColorDialogOption.NoButtons
)
self.opacity_spin = QDoubleSpinBox()
self.opacity_spin = QDoubleSpinBox(self)
self.opacity_spin.setRange(0, 1)
self.opacity_spin.setSingleStep(0.1)
self.opacity_spin.setDecimals(2)
Expand Down Expand Up @@ -233,7 +233,7 @@ class AdvancedWindow(QTabWidget):
:param image_view_names: passed as second argument to :py:class:`~.PColormapList`
"""

def __init__(self, settings: ViewSettings, image_view_names: List[str], reload_list=None, parent=None):
def __init__(self, settings: BaseSettings, image_view_names: List[str], reload_list=None, parent=None):
super().__init__(parent)
self.color_control = ColorControl(settings, image_view_names)
self.settings = settings
Expand Down
8 changes: 4 additions & 4 deletions package/PartSeg/common_gui/algorithms_description.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def _pretty_print(data, indent=2) -> str:


class ProfileSelect(QComboBox):
def __init__(self):
super().__init__()
def __init__(self, parent=None):
super().__init__(parent=parent)
self._settings = None

def _update_choices(self):
Expand Down Expand Up @@ -189,7 +189,7 @@ def _get_numeric_field(ap: AlgorithmProperty):
@classmethod
def _get_field_from_value_type(cls, ap: AlgorithmProperty):
if issubclass(ap.value_type, Channel):
res = ChannelComboBox()
res = ChannelComboBox(parent=None)
res.change_channels_num(10)
elif issubclass(ap.value_type, AlgorithmDescribeBase):
res = SubAlgorithmWidget(ap)
Expand All @@ -205,7 +205,7 @@ def _get_field_from_value_type(cls, ap: AlgorithmProperty):
elif issubclass(ap.value_type, ROIExtractionProfile):
res = ProfileSelect()
elif issubclass(ap.value_type, list):
res = QComboBox()
res = QComboBox(parent=None)
res.addItems(list(map(str, ap.possible_values)))
elif issubclass(ap.value_type, BaseModel):
res = FieldsList([cls.from_algorithm_property(x) for x in base_model_to_algorithm_property(ap.value_type)])
Expand Down
6 changes: 3 additions & 3 deletions package/PartSeg/common_gui/collapse_checkbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class CollapseCheckbox(QCheckBox):
Check box for hide widgets. It is painted as:
▶, {info_text}, line
If triangle is ▶ then widgets are hidden
If triangle is ▼ then widgets are shown
If triangle is ▶ then widgets are hidden.
If triangle is ▼ then widgets are shown.
:param info_text: optional text to be show
"""
Expand All @@ -25,7 +25,7 @@ def __init__(self, info_text: str = "", parent: typing.Optional[QWidget] = None)
self.stateChanged.connect(self.hide_element)

metrics = QFontMetrics(QFont())
self.text_size = metrics.size(Qt.TextSingleLine, info_text)
self.text_size = metrics.size(Qt.TextFlag.TextSingleLine, info_text)
self.info_text = info_text

def add_hide_element(self, val: QWidget):
Expand Down
6 changes: 3 additions & 3 deletions package/PartSeg/common_gui/colormap_creator.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ def paintEvent(self, a0: QPaintEvent) -> None:
for pos_factor in self.position_list:
pos = width * pos_factor
point = QPointF(pos + margin, self.height() / 2)
painter.setBrush(QBrush(Qt.black))
painter.setBrush(QBrush(Qt.GlobalColor.black))
painter.drawEllipse(point, 5, 5)
painter.setBrush(QBrush(Qt.white))
painter.setBrush(QBrush(Qt.GlobalColor.white))
painter.drawEllipse(point, 3, 3)

painter.restore()
Expand Down Expand Up @@ -495,7 +495,7 @@ def __init__(
self.colormap_map = colormap_map
self._widget_dict: Dict[str, ChannelPreview] = {}
self.scroll_area = QScrollArea()
self.central_widget = QWidget()
self.central_widget = QWidget(self)
layout2 = QVBoxLayout()
self.grid_layout = QGridLayout()
layout2.addLayout(self.grid_layout)
Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/common_gui/custom_load_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def __init__(

def accept(self):
super().accept()
if self.result() != QFileDialog.Accepted:
if self.result() != QFileDialog.DialogCode.Accepted:
return
directory = dirname(self.selectedFiles()[0])
self.settings.add_path_history(directory)
Expand Down
10 changes: 5 additions & 5 deletions package/PartSeg/common_gui/custom_save_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ def __init__(
parent=None,
caption="Save file",
history: typing.Optional[typing.List[str]] = None,
file_mode=QFileDialog.AnyFile,
file_mode=QFileDialog.FileMode.AnyFile,
):
super().__init__(save_register, caption, parent)
self.setFileMode(file_mode)
self.setOption(QFileDialog.DontUseNativeDialog, not system_widget)
self.setAcceptMode(QFileDialog.AcceptSave)
self.setOption(QFileDialog.Option.DontUseNativeDialog, not system_widget)
self.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
self.filterSelected.connect(self.change_filter)
self.accepted_native = False
self.values = {}
Expand Down Expand Up @@ -161,7 +161,7 @@ def __init__(
base_values: typing.Optional[dict] = None,
parent=None,
caption="Save file",
file_mode=QFileDialog.AnyFile,
file_mode=QFileDialog.FileMode.AnyFile,
):
if default_directory is None:
default_directory = str(Path.home())
Expand All @@ -183,7 +183,7 @@ def __init__(

def accept(self):
super().accept()
if self.result() != QDialog.Accepted:
if self.result() != QDialog.DialogCode.Accepted:
return
directory = os.path.dirname(self.selectedFiles()[0])
self.settings.add_path_history(directory)
Expand Down
6 changes: 3 additions & 3 deletions package/PartSeg/common_gui/error_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,9 @@ def __init__(
else:
exception, traceback_summary = exception
if isinstance(exception, SegmentationLimitException):
super().__init__(f"{exception}", parent, QListWidgetItem.UserType)
super().__init__(f"{exception}", parent, QListWidgetItem.ItemType.UserType)
elif isinstance(exception, Exception):
super().__init__(f"{type(exception)}: {exception}", parent, QListWidgetItem.UserType)
super().__init__(f"{type(exception)}: {exception}", parent, QListWidgetItem.ItemType.UserType)
self.setToolTip("Double click for report")
self.exception = exception
self.additional_info = traceback_summary
Expand Down Expand Up @@ -357,7 +357,7 @@ class QMessageFromException(QMessageBox):
"""

def __init__(self, icon, title, text, exception, standard_buttons=QMessageBox.Ok, parent=None):
def __init__(self, icon, title, text, exception, standard_buttons=QMessageBox.StandardButton.Ok, parent=None):
super().__init__(icon, title, text, standard_buttons, parent)
self.exception = exception
stream = io.StringIO()
Expand Down
4 changes: 2 additions & 2 deletions package/PartSeg/common_gui/flow_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ def doLayout(self, rect, testOnly):
wid = item.widget()
if wid is not None:
space_x = self.spacing() + wid.style().layoutSpacing(
QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal
QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Horizontal
)
space_y = self.spacing() + wid.style().layoutSpacing(
QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical
QSizePolicy.ControlType.PushButton, QSizePolicy.ControlType.PushButton, Qt.Orientation.Vertical
)
else:
space_x = self.spacing() # + wid.layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton,
Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/common_gui/image_adjustment.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(self, image: Image, transform_dict: Optional[Dict[str, TransformBas
for key, val in transform_dict.items():
self.choose.addItem(key)
initial_values = val.calculate_initial(image)
form_widget = FormWidget(val.get_fields_per_dimension(image.get_dimension_letters()), initial_values)
form_widget = FormWidget(val.get_fields_per_dimension(list(image.get_dimension_letters())), initial_values)
self.stacked.addWidget(form_widget)

self.choose.currentIndexChanged.connect(self.stacked.setCurrentIndex)
Expand Down
16 changes: 8 additions & 8 deletions package/PartSeg/common_gui/multiple_file_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class MultipleFilesTreeWidget(QTreeWidget):
def __init__(self, compare, parent=None):
super().__init__(parent)
self.compare = compare
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.customContextMenuRequested.connect(self.showContextMenu)

def showContextMenu(self, point):
Expand All @@ -67,7 +67,7 @@ def set_show_compare(self, compare: bool):
self.compare = compare

def mouseMoveEvent(self, event): # pylint: disable=no-self-use
QApplication.setOverrideCursor(Qt.ArrowCursor)
QApplication.setOverrideCursor(Qt.CursorShape.ArrowCursor)
super().mouseMoveEvent(event)


Expand All @@ -76,22 +76,22 @@ def __init__(self, settings: BaseSettings, parent=None):
super().__init__(parent)
self.settings = settings
self.file_list = QListWidget()
self.file_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.file_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
self.cancel_btn = QPushButton("Cancel", clicked=self.reject)
self.load_btn = QPushButton("Load", clicked=self.accept)

for name_list, method in settings.get_last_files_multiple():
entry = f"{name_list[0]} {method}"
item = QListWidgetItem(entry, self.file_list)
item.setData(Qt.UserRole, (name_list, method))
item.setData(Qt.ItemDataRole.UserRole, (name_list, method))

last_set = {(tuple(x), y) for x, y in settings.get_last_files_multiple()}
for name_list, method in settings.get_last_files():
if (tuple(name_list), method) in last_set:
continue
entry = f"{name_list[0]} {method}"
item = QListWidgetItem(entry, self.file_list)
item.setData(Qt.UserRole, (name_list, method))
item.setData(Qt.ItemDataRole.UserRole, (name_list, method))

layout = QGridLayout()
layout.addWidget(QLabel("Select files"))
Expand All @@ -105,7 +105,7 @@ def __init__(self, settings: BaseSettings, parent=None):
)

def get_files(self) -> List[Tuple[List[str], str]]:
return [item.data(Qt.UserRole) for item in self.file_list.selectedItems()]
return [item.data(Qt.ItemDataRole.UserRole) for item in self.file_list.selectedItems()]

def accept(self) -> None:
self.settings.set_in_profile("multiple_files_dialog_size", (self.size().width(), self.size().height()))
Expand Down Expand Up @@ -281,7 +281,7 @@ def save_state_action(self, state: ProjectInfoBase, custom_name):
except ValueError:
metric = QFontMetrics(self.file_view.font())
width = self.file_view.width() - 45
clipped_text = metric.elidedText(normed_file_path, Qt.ElideLeft, width)
clipped_text = metric.elidedText(normed_file_path, Qt.TextElideMode.ElideLeft, width)
item = QTreeWidgetItem(self.file_view, [clipped_text])
item.setToolTip(0, normed_file_path)
self.file_list.append(normed_file_path)
Expand Down Expand Up @@ -382,7 +382,7 @@ class MultipleLoadDialog(CustomLoadDialog):
def __init__(self, load_register, history=None):
load_register = {key: val for key, val in load_register.items() if not val.partial()}
super().__init__(load_register=load_register, history=history)
self.setFileMode(QFileDialog.ExistingFiles)
self.setFileMode(QFileDialog.FileMode.ExistingFiles)

def accept(self):
self.files_list.extend(self.selectedFiles())
Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/common_gui/napari_image_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def __init__(
self.search_roi_btn.clicked.connect(self._search_component)
self.search_roi_btn.setDisabled(True)
self.roll_dim_button = QtViewerPushButton(self.viewer, "roll", "Roll dimension", self._rotate_dim)
self.roll_dim_button.setContextMenuPolicy(Qt.CustomContextMenu)
self.roll_dim_button.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.roll_dim_button.customContextMenuRequested.connect(self._dim_order_menu)
self.mask_chk = QCheckBox()
self.mask_chk.setVisible(False)
Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/common_gui/numpy_qimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, image: np.ndarray):
image.shape[1],
image.shape[0],
image.dtype.itemsize * image.shape[1] * image.shape[2],
QImage.Format_RGBA8888,
QImage.Format.Format_RGBA8888,
)
self.image = image

Expand Down
10 changes: 5 additions & 5 deletions package/PartSeg/common_gui/qt_modal.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""from napari._qt.dialog.modal """
from qtpy.QtCore import QPoint, QRect, Qt
from qtpy.QtGui import QCursor, QGuiApplication
from qtpy.QtGui import QCursor, QGuiApplication, QKeyEvent
from qtpy.QtWidgets import QDialog, QFrame, QVBoxLayout


Expand Down Expand Up @@ -37,7 +37,7 @@ def __init__(self, parent):
super().__init__(parent)
self.setObjectName("QtModalPopup")
self.setModal(False) # if False, then clicking anywhere else closes it
self.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint)
self.setWindowFlags(Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
self.setLayout(QVBoxLayout())

self.frame = QFrame()
Expand Down Expand Up @@ -121,15 +121,15 @@ def move_to(self, position="top", *, win_ratio=0.9, min_length=0):
top = max(min(screen_geometry.bottom() - height, top), screen_geometry.top())
self.setGeometry(left, top, width, height)

def keyPressEvent(self, event):
def keyPressEvent(self, event: QKeyEvent):
"""Close window on return, else pass event through to super class.
Parameters
----------
event : qtpy.QtCore.QEvent
event : qtpy.QtGui.QKeyEvent
Event from the Qt context.
"""
if event.key() in (Qt.Key_Return, Qt.Key_Enter):
if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
self.close()
return
super().keyPressEvent(event)
8 changes: 4 additions & 4 deletions package/PartSeg/common_gui/searchable_combo_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ def __init__(self, parent=None):
super().__init__(parent)
self.setEditable(True)
self.completer_object = QCompleter()
self.completer_object.setCaseSensitivity(Qt.CaseInsensitive)
self.completer_object.setCompletionMode(QCompleter.PopupCompletion)
self.completer_object.setFilterMode(Qt.MatchContains)
self.completer_object.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.completer_object.setCompletionMode(QCompleter.CompletionMode.PopupCompletion)
self.completer_object.setFilterMode(Qt.MatchFlag.MatchContains)
self.setCompleter(self.completer_object)
self.setInsertPolicy(QComboBox.NoInsert)
self.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
if parse(QT_VERSION) < parse("5.14.0"): # pragma: no cover
self.currentIndexChanged.connect(self._text_activated)

Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/common_gui/searchable_list_widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __getattr__(self, item):
return super().__getattr__(item)

def update_visible(self, text):
items_text = [x.text() for x in self.list_widget.findItems(text, Qt.MatchContains)]
items_text = [x.text() for x in self.list_widget.findItems(text, Qt.MatchFlag.MatchContains)]
for index in range(self.list_widget.count()):
item = self.item(index)
item.setHidden(item.text() not in items_text)
Expand Down
Loading

0 comments on commit 107c615

Please sign in to comment.