'PyQt5 tray program closes after QDialog executing [duplicate]
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QCheckBox, QSystemTrayIcon, \
QSpacerItem, QSizePolicy, QMenu, QAction, QStyle, qApp, QPushButton
from PyQt5.QtCore import QSize
from PyQt5 import QtWidgets
class MainWindow(QMainWindow):
check_box = None
tray_icon = None
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(480, 80))
self.setWindowTitle("System Tray Application")
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
grid_layout = QGridLayout(self)
central_widget.setLayout(grid_layout)
grid_layout.addWidget(QLabel("Application, which can minimize to Tray", self), 0, 0)
self.check_box = QCheckBox('Minimize to Tray')
grid_layout.addWidget(self.check_box, 1, 0)
grid_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2, 0)
self.btn = QPushButton('Dialog', self)
grid_layout.addWidget(self.btn, 1, 1)
self.btn.clicked.connect(self.dial_func)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))
show_action = QAction("Show", self)
quit_action = QAction("Exit", self)
hide_action = QAction("Hide", self)
dial = QAction('Dial', self)
dial.triggered.connect(self.dial_func)
show_action.triggered.connect(self.show)
hide_action.triggered.connect(self.hide)
quit_action.triggered.connect(qApp.quit)
tray_menu = QMenu()
tray_menu.addAction(show_action)
tray_menu.addAction(hide_action)
tray_menu.addAction(dial)
tray_menu.addAction(quit_action)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.show()
def closeEvent(self, event):
if self.check_box.isChecked():
event.ignore()
self.hide()
self.tray_icon.showMessage(
"Tray Program",
"Application was minimized to Tray",
QSystemTrayIcon.Information,
2000
)
def dial_func(self):
text, ok = QtWidgets.QInputDialog.getText(self, 'Input dialog', 'Enter your name')
if ok:
print('simple text', text)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec())
I am trying to write little application for diagnostic. Application should work in tray and have options to change settings from QDialog. With this code, I can run dialog from btn (in main window) and from Dial (from QMenu). And if program not in tray, everything works fine, but if it's in tray, program finishes. What's way to solve this problem?
Solution 1:[1]
I think you need to call the show function when calling the dialog window.
def dial_func(self):
self.show()
text, ok = QtWidgets.QInputDialog.getText(
self, 'Input dialog', 'Enter your name')
if ok:
print('simple text', text)
This solution will solve your issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | taipei |
