1

I am currently working on a tray app in python/pyside2. I am trying to create custom QMenu items (containing QLabels and QProgressBars). I managed to get the basic functionality, but the alignment and font size of QLabels is different than the regular QAction menu items. I worked around the alignment issue with QLayout margins, but these are hard-coded sizes, and I am sure there is a way to get the correct values somehow.

Here is the demo code:

from PySide2.QtGui import *
from PySide2.QtWidgets import *


def quit_action_clicked():
    app.quit()


def test_action_clicked():
    pass


if __name__ == "__main__":

    app = QApplication([])
    app.setQuitOnLastWindowClosed(False)
    icon = QIcon("assets/icons.iconset/icon_128x128.png")

    tray = QSystemTrayIcon()
    tray.setIcon(icon)
    tray.setVisible(True)

    menu = QMenu()
    add_action = QAction("Barfoobaz")
    menu.addAction(add_action)
    test_action = QAction("Foobarbaz")
    test_action.triggered.connect(test_action_clicked)
    menu.addAction(test_action)
    menu.addSeparator()

    widget = QWidget()
    layout = QVBoxLayout()
    innerLayout = QGridLayout()
    innerLayout.setSpacing(2)
    innerLayout.setContentsMargins(0, 0, 0, 3)
    innerLayout.addWidget(QLabel("Name:"), 0, 0)
    innerLayout.addWidget(QLabel("tank"), 0, 1)
    innerLayout.addWidget(QLabel("GUID:"), 1, 0)
    innerLayout.addWidget(QLabel("12345678901234567890"), 1, 1)
    innerLayout.addWidget(QLabel("Status:"), 2, 0)
    innerLayout.addWidget(QLabel("healthy"), 2, 1)
    layout.addLayout(innerLayout)
    bar = QProgressBar()
    bar.setValue(70)
    layout.addWidget(bar)
    layout.addWidget(QLabel("Size: 2TB, 1.87TB free"))
    layout.setContentsMargins(21, 0, 15, 0)
    layout.setSpacing(0)
    widget.setLayout(layout)
    berAction = QWidgetAction(menu)
    berAction.setDefaultWidget(widget)

    menu.addAction(berAction)
    menu.addSeparator()
    action = QAction("Quit")
    action.triggered.connect(quit_action_clicked)

    menu.addAction(action)
    tray.setContextMenu(menu)
    app.exec_()

And here is how it looks:

enter image description here

Is there any way to:

  • get the right margin values to match standard menu items
  • get the font to match standard menu items
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
REjsmont
  • 63
  • 5
  • `print( add_action.font() )` gives me font used in `QAction`. May other information you could also get from `QAction` and use them in `QLabel`. Maybe it will work `QLabel(... font=add_action.font())` – furas Dec 02 '19 at 00:21
  • 1
    This, unfortunately, does not work. Interestingly, I compared QFontInfo from QAction and QLabel and they are exactly the same, yet in the rendering, both have a slightly different size. I measured the difference to be 1 pixel. That's little but very annoying. Could this be a bug in Qt? – REjsmont Dec 02 '19 at 08:48

0 Answers0