0

我想将对话框与SysTrayIcon. 应用程序运行的原因是systray,并在您按下图标按钮时显示对话框。该应用程序将仅从菜单选项中完全关闭。

要解决的问题:当失去焦点时(例如:点击outisde),即使对话框有一个按钮来显示模态窗口,他的对话框也应该隐藏

请测试示例代码,因为它说明了一切。

from PySide2.QtWidgets import *
import sys


message = '''
This is a dialog we wanna use together with the SysTrayIcon
The reason of the app is running in a systray, and show the
dialog when you press the icon button. The app will close
entirely from the menu option, explained below.

Clicking SysTray icon use:
1) Click left and right in icon it shows the app
   and you can interact with it. If you click again it toggles
   show/hide the app.
2) With Middle Click a menu shows up, and dialog hides.
   From this menu you can close the app entirely.

PROBLEM TO SOLVE:
When lose focus(eg:clicking outisde) he dialog should hide
Even if the dialog had a button to display a modal window
'''

class LauncherDialog(QDialog):
    def __init__(self, x=None, y=None, parent=None):
        super(LauncherDialog, self).__init__(parent)

        my_lbl = QLabel(message)
        my_layout = QVBoxLayout()
        my_layout.addWidget(my_lbl)
        my_layout.setMargin(0)

        self.setLayout(my_layout)
        self.setMinimumHeight(630)
        self.setMinimumWidth(360)

        self.setWindowTitle("Launcher")

        if x is not None and y is not None:
            self.move(x, y)

class SystrayLauncher(object):

    def __init__(self):
        # Create the icon
        w = QWidget() #just to get the style(), haven't seen other way
        icon = w.style().standardIcon(QStyle.SP_MessageBoxInformation)

        # Create the tray
        self.tray = QSystemTrayIcon()
        self.tray.setIcon(icon)
        self.tray.setVisible(True)
        self.tray_pos = self.tray.geometry()
        left = self.tray_pos.left()
        height = self.tray_pos.height()

        self.menu = QMenu()
        self.action = QAction("&Quit", None, triggered=QApplication.instance().quit)
        self.tray.setContextMenu(self.menu)

        self.launcher_window = LauncherDialog(x=left, y=height)
        self.tray.activated.connect(self.handleLeftRightMiddleClick)

    def handleLeftRightMiddleClick(self, signal):
        if signal == QSystemTrayIcon.ActivationReason.MiddleClick:
            self.menu.addAction(self.action) #show menu
            self.launcher_window.hide()
        elif signal == QSystemTrayIcon.ActivationReason.Trigger: #left / right clicks
            self.menu.removeAction(self.action) #hide menu
            if self.launcher_window.isHidden():
                self.launcher_window.show()
            else:
                self.launcher_window.hide()
        else: #doubleclick
            pass


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)

    sl = SystrayLauncher()
    sys.exit(app.exec_())
4

0 回答 0