Running sample code, but icon not show

I run the following sample code that comes with the PySide2 ebook

import sys
from PySide2.QtCore import QSize, Qt
from PySide2.QtGui import QIcon
from PySide2.QtWidgets import (
    QApplication,
    QLabel,
    QMainWindow,
    QToolBar,
    QAction,
    QStatusBar,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My App")
        label = QLabel("Hello!")
        label.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(label)
        toolbar = QToolBar("My main toolbar")
        toolbar.setIconSize(QSize(16, 16))

        # I also tried this, but it still doesn't work
        toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.addToolBar(toolbar)

        # @@@ Attach icon to QAction
        button_action = QAction(QIcon("bug.png"), "Your button", self)
        button_action.setStatusTip("This is your button")
        button_action.triggered.connect(self.onMyToolBarButtonClick)
        button_action.setCheckable(True)
        toolbar.addAction(button_action)
        self.setStatusBar(QStatusBar(self))

    def onMyToolBarButtonClick(self, s):
        print("click", s)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

The bug.png image is sitting next to the source code toolbars_and_menus_5.py. But for some reason my GUI output doesn’t show any icon at all.

image

Any idea what went wrong?
I am running on macOS Catalina (v10.15.6) + Python 3.7 + pip install PySide2.
I also tried on Win10 Pro + Python 3.7 + pip install PySide2 .
Same problem. The icon is still missing.

Thanks

I was trying to reinstall PySide2 with homebrew on macOS. I realize another problem with the ebook.

$ brew install pyside2 

Is invalid because Homebrew doesn’t have the PySide2 package. It only has PySide. Kinda confusing…

Found the root cause!
My python script was run from VScode’s “run” button. The script was called from another folder location with absolute path. But the icon file path in the script has a relative path. That’s why python interpreter could not find the icon file. So a simple fix is to turn the icon file into absolute path.

from pathlib important Path

icon_path = str(Path(__file__).parent / "bug.png")
button_action = QAction(QIcon(icon_path), "Your button", self)
1 Like

Thanks for posting the solution @Scoodood – I was thinking it might have something weird to do with png libraries, nice to know it’s something simpler. I think you can also change the working directory at the beginning of your script to match the location of the file being with.

import os
path = os.path.dirname(__file__)
os.chdir(path)

You can also get the absolute path with

os.path.abspath(__file__)

I was trying to reinstall PySide2 with homebrew on macOS. I realize another problem with the ebook.

Thanks again, I’ll fix this in the next update.