this post was submitted on 09 Feb 2025
30 points (100.0% liked)

Python

6628 readers
115 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS
 

I'm working on a project that needs lots of toolbars on screen at once, even though not all of them will be used at the same time. So, I'm modelling this 'foldable' dock widget after what I remember Photoshop panels used to be like.

It's a work in progress, but would like to hear constructive suggestions.

https://blocks.programming.dev/0101100101/42c5d67f86c049baa3500aa38e439f8a

top 14 comments
sorted by: hot top controversial new old
[–] logging_strict@programming.dev 3 points 22 hours ago (1 children)

Lets fix the Sphinx in-code documentation (Ignoring should never embed classes within other classes)

class FoldableDockWidget(QDockWidget):
    """
    A simple Qt Widget that adds a 'minimise' button that vertically reduces the dock widget to just the titlebar to
    allow the dock widget to still take up minimal screen real estate
    """

    class TitleBarWidget(QWidget):
        def __init__(self, title:str, parent:QWidget=None):
            """
            We create a custom title bar using QWidget as the base. The title bar has to be wrapped in another widget
            so that its background can be styled easier, otherwise it's impossible to style
            :param title: the title to appear in the title bar
            """

Becomes

class FoldableDockWidget(QDockWidget):
    """
    A simple Qt Widget that adds a 'minimise' button that vertically reduces the dock widget to just the titlebar to
    allow the dock widget to still take up minimal screen real estate
    """

    class TitleBarWidget(QWidget):
    """Create a custom title bar using :py:class:`~PySide6.QtWidgets.QWidget` as the base.
    The title bar has to be wrapped in another widget so that its background can be styled
    easier, otherwise it's impossible to style

    :ivar title: the title to appear in the title bar
    :vartype title: str
    :ivar parent: Default None. Identify parent widget
    :vartype parent: PySide6.QtWidgets.QWidget | None
    """

        def __init__(self, title: str, parent: QWidget = None) -> None:
            """class constructor"""

typing matters. Normally separate typing into stub files. The Sphinx in-code documentation includes typing, so the signatures can be simplified and easier to read

def __init__(self, title, parent=None):

[–] 0101100101@programming.dev 2 points 19 hours ago* (last edited 7 hours ago) (1 children)

Thanks for your response.

should never embed classes within other classes)

Why is this? I have to admit that coming from other languages, it feels dirty, but is there a pythonic good reason for this? The class 'belongs' to the FoldableDockWidget class, so I figure it's the best place to put it.

Arguing for modularity. Which isn't likely in a gist (or a script), but is normal for a package.

By embedding the class, creates a limitation that prevents abstractions or other implementations of each component. Imagine every suggestion in this conversation thread is another variation with a separate implementation.

The widget class belongs to the FoldableDockWidget class until it doesn't. Then a refactor is needed.

There should be four modules. The entrypoint (and cli options parsing), the application, the dockwidget, and the widget. Each should be testable by itself.

A widget is not a container. An application is not a container component (avoiding the word widget). Hardwiring a particular implementation of the Windowing Python wrapper is also unnecessary (PySide6). What about PySide2, pyQt5, pyQt6, and whatever else comes next?

As a side note

Why is there code in the process guard, besides main() (or a async equivalent)? Only multiprocessing applications have code within the process guard. Code within the process guard is unreachable; can't be imported. For example, testing just the cli option parsing.

[–] FizzyOrange@programming.dev 3 points 23 hours ago (1 children)

Easily above average code for Python. I'm going to pick on one method:

def _set_float_icon(self, is_floating: bool):
            """ set the float icon depending on the status of the parent dock widget """
            if is_floating:
                self.float_button.setIcon(self.icon_dock)
            else:
                self.float_button.setIcon(self.icon_float)

First, Python does have ternary expressions so you can

self.float_button.setIcon(self.icon_dock if is_floating else self.icon_float)

Second, what does this code do?

foo._set_float_icon(true)

Kind of surprising that it sets the icon to icon_dock right? There are two easy fixes:

  1. Use *, is_floating: bool so you have to name the parameter when you call it.
  2. I'd probably rename it to _update_float_icon() or something.

Also use Black or Ruff to auto-format your code (it's pretty well formatted already but those will still improve it and for zero effort).

[–] logging_strict@programming.dev 1 points 22 hours ago (1 children)

ternary expressions

Recommend against the ternary expression. coverage might not detect the two code blocks. Would also not be able to apply # pragma: no cover comment to a code block that isn't important enough to justify testing it. Often use do nothing code blocks.

self.float_button.setIcon(self.icon_dock if is_floating else self.icon_float) lets say while testing something goes wrong and trying to debug what happened.

Will not see the value that gets past into self.float_button.setIcon

I like your idea of having the param be keyword only. Makes it more readable.

[–] FizzyOrange@programming.dev 1 points 13 hours ago (1 children)

If you branch coverage tool can't handle branches on the same line I would suggest you use a different one! Does it handle if foo or bar?

Will not see the value that gets past into self.float_button.setIcon

Uhm, yes you will? Just step into the function.

self.float_button.setIcon is a Python wrapper around a C++ library. Might not be possible to, or want to, step into the function.

if foo or bar is part of a if-else condition. The else portion needs # pragma: no cover or coverage may complain.

[–] logging_strict@programming.dev 1 points 22 hours ago* (last edited 22 hours ago)
from PySide6.QtWidgets import QDockWidget, QWidget, QToolButton, QStyle, QHBoxLayout, QStyleFactory, QSizePolicy, \
    QApplication, QVBoxLayout, QLabel, QSlider, QMainWindow, QSizeGrip

No code should be more than 80 characters UNLESS it's unavoidable like with a long regex. Hard limit is normally 88 characters.

Should be

from PySide6.QtWidgets import (
    QDockWidget,
    QWidget,
    QToolButton,
    QStyle,
    QHBoxLayout,
    QStyleFactory,
    QSizePolicy,
    QApplication,
    QVBoxLayout,
    QLabel,
    QSlider,
    QMainWindow,
    QSizeGrip,
)

Or add parenthesis and the last comma. black will reformat it. Then use isort to fix imports ordering.

Get that you are sharing this as a gist. Normally code like this is broken up into multiple modules so it's easier on the eyes and less going on.

[–] Yareckt@lemmynsfw.com 1 points 23 hours ago* (last edited 23 hours ago)

I don't know anything about qt. But I can criticise the design a bit. If something isn't possible to realize in qt then I apologise.

  1. The Label may not need to be displayed in a separate line. You maybe could put the basic information abpu the window into the windows title and display additional information from the label when hovering over the title.
  2. The sliders have no way to display what the concrete value selected with the slider is. You may want to include the concrete value next to the slider name.
  3. The 3 buttons in the windows top box could be reduced. From a use case perspective being able to hide the tool window and then restore it at the same position is the same as being able to collapse it.
  4. A kind of spacer between the sliders and the next sliders name could make it faster to identify which slider belongs to which name. Don't know what would look good but you could try leaving a tiny bit more space between them or including some thin lines that don't touch the windows edges.
[–] ulterno@programming.dev 2 points 1 day ago* (last edited 1 day ago) (1 children)

Nice.

Depending upon what you are aiming for, I'd go with a sidebar. Something like this:

Illustrating the idea of widgets in a sidebar

  • (a) The sidebar's horizontal width can be changed, causing all docked widgets in it to resize their width to fit.
  • (b) The docked widgets/sections may resize vertically, either automatically or manually
    • In case of manual resizing of widgets, you might want to add a scroll area in the widget
  • (c) A widget/section may leave empty area in the bottom or vertically expand to fill
  • (d) In case of empty area, the sidebar can either have empty space or be vertically shortened to expose part of the workspace underneath
  • (e) Instead of having just a single widget, you can have a section on the toolbar, with multiple widgets in it. In this case, when the user changes the tab, the section will either automatically resize (vertically) as per widget requirements, or will stay the size that the user set manually, adding a scrollbar in case of overflow or empty area in case of lack of widget content.

This is in contrast to usual sidebars that tend to have a main tab bar, which only allows for a single docked widget to be shown at a time. This will allow the user to stack widgets both vertically and horizontally as per their requirements. A similar example can be seen in the right side panel in the Design Mode of Qt Creator itself.
Folded widgets/sections, when docked, will yield vertical space to other widgets/sections, which will in turn, snap upwards (or you can do downwards if that's your fancy)

Maybe you can also make the floating widgets mergeable into tabs, which will reduce the number of point+click actions in cases where only 1 of 2 widgets is being used.


CC BY-NC-SA 4.0

[–] 0101100101@programming.dev 2 points 1 day ago* (last edited 1 day ago) (1 children)

Qt automatically handles the conversion of QDockWidgets into tabbed docked widgets when one is dragged over an existing one.

I have a little demo video, but I have no idea where to upload it to!

[–] ulterno@programming.dev 0 points 1 day ago

Oh! You actually used QDockWidget instead of making it from the start. I should have read the code before commenting, I guess.

[–] dohpaz42@lemmy.world 2 points 1 day ago (1 children)

Photoshop these days minimizes unused pallets into an icon on a vertical toolbar.

Something along these lines:

[–] 0101100101@programming.dev 2 points 1 day ago* (last edited 1 day ago)

Thanks. I wondered why I instinctively text-transformed the title of the widget to uppercase! I commented it out thinking perhaps it doesn't look grammatically correct! Reduced the font size a bit and I think it looks a heck of a lot better now!