Issue
I am new to PyQt6 and python. I created a class SystemTrayIcon
where I am trying to open a QWidget win
which was created outside the SystemTrayIcon
-class, to show up when the SystemTrayIcon got left-clicked.
I got this error: "name 'win' is not defined"
How can I fix this, that the win
-QWidget which was created outside the class SystemTrayIcon
will open when the SystemTrayIcon got left-clicked?
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
import sys
import ui_main
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, icon, win, parent=None):
QSystemTrayIcon.__init__(self, icon, parent)
self.setToolTip("Test SystemTray")
menu = QMenu(parent)
exit_ = menu.addAction("Exit")
exit_.triggered.connect(lambda: sys.exit())
self.setContextMenu(menu)
self.activated.connect(self.trayiconclicked)
def trayiconclicked(self, reason):
if reason == self.ActivationReason.Trigger:
print("SysTrayIcon left clicked")
win.show() ###### -> ERROR: (<class 'NameError'>, NameError("name 'win' is not defined"), <traceback object at 0x000001B04F5C9580>)
def run():
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
win = QWidget()
tray_icon = SystemTrayIcon(QIcon("images/logo.png"), win)
tray_icon.setVisible(True)
tray_icon.show()
ui = ui_main.Ui_Form()
ui.setupUi(win, tray_icon.geometry().right(), tray_icon.geometry().bottom(),
tray_icon.geometry().width(), tray_icon.geometry().height())
ui.btn_close.clicked.connect(lambda: win.close())
sys.exit(app.exec())
if __name__ == '__main__':
run()
Solution
It should work now you need to make win
its attribute before you call it
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, icon, win, parent=None):
QSystemTrayIcon.__init__(self, icon, parent)
self.setToolTip("Test SystemTray")
self.win = win # <----- name it whatever you want ie self.abc will also work
menu = QMenu(parent)
exit_ = menu.addAction("Exit")
exit_.triggered.connect(lambda: sys.exit())
self.setContextMenu(menu)
self.activated.connect(self.trayiconclicked)
def trayiconclicked(self, reason):
if reason == self.ActivationReason.Trigger:
print("SysTrayIcon left clicked")
self.win.show() # <--- if you named you attribute self.abc call self.abc here instead of self.win
NOTE: to make a variable a attribute of a class you need to define it with self eg, here I want to have age as a attribute
class Person:
def __init__(self, name, age):
# assigning attributes
self.age = age
def some_method(self):
# here calling self.name will give you error because you didn't assign it as a attribute
print(self.name)
def some_method_1(self):
# here this will not give error as you have assigned it earlier as a attribute
print(self.age)
p = Person("Bob", 16)
p.some_method_1()
p.some_method()
Answered By - Ibrahim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.