将对话框/窗口应用程序与SysTray图标一起使用:焦点问题

时间:2019-06-11 04:55:47

标签: python pyside2 systray

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

要解决的问题:当失去焦点(例如单击过时)时,即使对话框中有显示模式窗口的按钮,对话框也应隐藏

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

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_())

0 个答案:

没有答案