[英]PyQt6 - Open QWidget by left clicking the SystemTrayIcon
我是 PyQt6 和 python 的新手。 我創建了一個 class SystemTrayIcon
,我試圖打開一個在SystemTrayIcon
類之外創建的 QWidget win
,以便在 SystemTrayIcon 被left-clicked時顯示。
我收到此錯誤: "name 'win' is not defined"
我該如何解決這個問題,當左鍵單擊SystemTrayIcon 時,在 class SystemTrayIcon
之外創建的win
-QWidget 將打開?
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()
它現在應該可以工作了,您需要在調用它之前使win
其屬性
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
注意:要使變量成為 class 的屬性,您需要使用 self 定義它,例如,這里我想將年齡作為屬性
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.