shortcut doesn't work in PyQt5 in tray dropdown menu - python

I was trying to set a shortcut for dropdown menu. The code is below
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QAction
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
super(SystemTrayIcon, self).__init__(icon, parent)
menu = QtWidgets.QMenu(parent)
# add actions and shortcuts for them.
exitAction = QAction('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(parent.close)
menu.addAction(exitAction)
restoreAction = QAction('Restore', self)
restoreAction.setShortcut("Ctrl+R")
restoreAction.triggered.connect(self.restore)
menu.addAction(restoreAction)
self.setContextMenu(menu)
def restore(self):
print 'restore'
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Icon')
self.tray_icon = SystemTrayIcon(QtGui.QIcon('/opt/WizNote/wiznote.png'), self)
self.tray_icon.show()
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
w = MainWindow()
sys.exit(app.exec_())
The shortcut doesn't work. Is there something wrong with my code?
Python2.7 and PyQt5 was installed in my laptop.

I had exactly the same problem as yours, and I solved it by respecting the following pattern for each action:
menu.addAction(exitAction)
parent.addAction(exitAction) # line to be added

Related

PyQt using classes to show button

Getting very stuck here, I am trying to learn how to use classes, and so simply want to show a button on a window when the button is in a different class. Here is the code I am trying to use:
#!/usr/bin/python3
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(0, 0, 800, 600)
main_menu = Menu()
self.show()
class Menu(QtGui.QWidget):
def __init__(self):
btn = QtGui.QPushButton("Quit")
btn.resize(btn.sizeHint())
btn.move(100,100)
btn.show()
print("Hello I am a menu")
def main():
app = QtGui.QApplication(sys.argv)
main_window = Window()
sys.exit(app.exec())
if __name__ == "__main__":
main()
This works so far as I get a window, but no button on it, howerver the print message I put in works. What am I doing wrong please?
You must initialize the parent class in Menu, in addition to passing the parent to that class and the button.
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(0, 0, 800, 600)
main_menu = Menu(self)
self.show()
class Menu(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
btn = QtGui.QPushButton("Quit", self)
btn.resize(btn.sizeHint())
btn.move(100,100)
print("Hello I am a menu")
def main():
app = QtGui.QApplication(sys.argv)
main_window = Window()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Make a modal QDialog minimize when QMainWindow minimized (using PyQt 5)

Example code I am using:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.open_about = False
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def about_state_upd(self, value):
self.open_about = value
def aboutDialog(self):
self._about = AboutDialog(self)
self._about.exec_()
def hideEvent(self, hideEvent):
if self.open_about == True:
self._about.setVisible(False)
def showEvent(self, showEvent):
if self.open_about == True:
if self._about.isHidden() == True:
self._about.setModal(True)
self._about.setVisible(True)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
self.parent().about_state_upd(True)
def closeEvent(self, closeEvent):
self.parent().about_state_upd(False)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
This code basically works, but seems very complicated. Is there a simpler / cleaner way to make it so that when the modal QDialog is open, if the QMainWindow is minimized, the QDialog also gets minimized too (and reverse when QMainWindow is restored)?
Code is running on KDE Neon (Kubuntu-based distro).
May be you can use this: http://korbinin.blogspot.fr/search/label/minimize%20button
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainForm(QDialog):
def __init__(self, fn=None,parent=None):
super(MainForm, self).__init__(parent,\
flags=Qt.WindowMinimizeButtonHint|Qt.WindowMaximizeButtonHint)
Thanks to the people on the PyQt Mailing list, I managed to get a workaround for KDE. Instead of using exec_(), I am just using show() - then I use setDisabled() on QMainWindow to make dialog act in a modal fashion. Here is a (very quick and basic) example for anyone interested:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def aboutDialog(self):
self._about = AboutDialog(self)
self.setDisabled (True)
self._about.show()
def enableWidgets(self):
self.setDisabled(False)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
def closeEvent(self, parent):
self.parent().enableWidgets()
def changeEvent(self, event):
if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized:
self.parent().showMinimized()
else:
self.parent().showMaximized()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
Link to PyQt Mailing List posts.

PyQt signal slot issue with signal outside creating class

I am trying to create a toolbar that can be modified to change actions on the fly.
However signals are not being sent when I add actions from outside the class that creates the toolbar.
In the example below the new action is never triggered. Any idea on how this can be done?
import sys
from PyQt4 import QtGui
from toolbarmodifier import ToolbarModifier
class FluidToolbar(QtGui.QMainWindow):
def __init__(self):
super(FluidToolbar, self).__init__()
self.initUI()
def initUI(self):
createAction = QtGui.QAction( 'create Action', self)
createAction.triggered.connect(self.createActions)
self.toolbar = self.addToolBar('create Action')
self.toolbar.addAction(createAction)
self.setGeometry(300, 300, 300, 200)
self.show()
def createActions(self):
print(">>createActions()")
toolbarModifier = ToolbarModifier()
toolbarModifier.addAction(self)
def main():
app = QtGui.QApplication(sys.argv)
ex = FluidToolbar()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
toolbarmodifier.py
from PyQt4 import QtGui
from PyQt4.QtGui import QWidget
class ToolbarModifier(QWidget):
def __init__(self):
super(ToolbarModifier, self).__init__()
def newActionTriggered(self):
print(">>newActionTriggered()")
def addAction(self, gui):
triggerAction = QtGui.QAction( 'New action', gui)
triggerAction.triggered.connect(self.newActionTriggered)
gui.toolbar.addAction(triggerAction)
print("<<addAction()")
Not having a link back to parent was the issue. In FluidToobar modify code in createActions method to include self in call:
toolbarModifier = ToolbarModifier(self)
In ToolbarModifier change first few lines to:
class ToolbarModifier(QtCore.QObject):
def __init__(self, parent=None):
super(ToolbarModifier, self).__init__(parent)

How to add a Status to this PySide based ui

Look at the code
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
self.statusBar().showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
Now all I want to do , is add a Status. Now status is available in QtGui.QMainWindow
How can i use this fact to add it in the above program? In pyside coding , seems like for every component , we need to make a class and some connect to the main class..whata s the theory here?
I tried myself like this , but it did not work.
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
self.statusBar().showMessage('Ready')
self.s = MyStatus()
class MyStatus(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
You do not need to make a class for every component, but if you want to modify/override each component's built-in function you need to make a class for it.
To add something to your main window, you simply have to create an object and add it to the layout. As follow:
import sys
from PySide import QtGui , QtCore
class MyStatusBar(QtGui.QStatusBar):
def __init__(self, parent=None):
super(MyStatusBar, self).__init__(parent)
#Override any functions, or define new function for our status bar here
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
#Set the size of the window
self.setMinimumSize(300,300)
#Create a status bar, from our OWN class
self.status_bar = MyStatusBar(self)
self.status_bar.setGeometry(QtCore.QRect(0, 0, 50, 50))
self.status_bar.showMessage('Ready')
#Add a simple quit button, from the DEFAULT class
self.quit_button = QtGui.QPushButton(self)
self.quit_button.clicked.connect(self.close)
self.quit_button.setGeometry(QtCore.QRect(100, 100, 100, 35))
self.quit_button.setText("Close")
#Start the application
app = QtGui.QApplication(sys.argv)
top = MyMainWindow()
top.show()
app.exec_()
If you want a window with a status-bar, use QMainWindow: it has one built-in (and also a menu-bar, tool-bars, dock-widgets, etc). Other widgets don't have these built-in features, and so, quite naturally, they don't have things like a statusBar method. If you insist on doing things the hard way by not using QMainWindow, you will have to add all these features yourself.
Although I wouldn't recommend doing things this way, here is a simple demo that adds a status-bar to a QWidget:
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.central_widget = QtGui.QWidget(self)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
layout = QtGui.QVBoxLayout(self.central_widget)
layout.addWidget(self.quit)
self.status = QtGui.QStatusBar(self)
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.widget)
layout.addStretch()
layout.addWidget(self.status)
self.status.showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())

PyQt: Show menu in a system tray application

First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.
This code works, it shows the menu (I don't connect the exit action and so on to keep it simple)
import sys
from PyQt4 import QtGui
def main():
app = QtGui.QApplication(sys.argv)
trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app)
menu = QtGui.QMenu()
exitAction = menu.addAction("Exit")
trayIcon.setContextMenu(menu)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
But this doesn't:
import sys
from PyQt4 import QtGui
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtGui.QMenu()
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
def main():
app = QtGui.QApplication(sys.argv)
trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I probably miss something. There are no errors but in the second case when I click with the right button it doesn't show the menu.
Well, after some debugging I found the problem. The QMenu object it is destroyed after finish __init__ function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon which is an QWidget):
import sys
from PyQt4 import QtGui
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtGui.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
def main():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I think I would prefer the following as it doesn't seem to depend upon QT's internal garbage collection decisions.
import sys
from PyQt4 import QtGui
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
self.menu = QtGui.QMenu(parent)
exitAction = self.menu.addAction("Exit")
self.setContextMenu(self.menu)
def main():
app = QtGui.QApplication(sys.argv)
style = app.style()
icon = QtGui.QIcon(style.standardPixmap(QtGui.QStyle.SP_FileIcon))
trayIcon = SystemTrayIcon(icon)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Here is the code with Exit action implemented
import sys
from PyQt4 import QtGui, QtCore
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtGui.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtGui.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
QtCore.QObject.connect(exitAction,QtCore.SIGNAL('triggered()'), self.exit)
def exit(self):
QtCore.QCoreApplication.exit()
def main():
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon("qtLogo.png"), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Here is the PyQt5 version (was able to implement the Exit action of demosthenes's answer).
Source for porting from PyQt4 to PyQt5
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
# code source: https://stackoverflow.com/questions/893984/pyqt-show-menu-in-a-system-tray-application - add answer PyQt5
#PyQt4 to PyQt5 version: https://stackoverflow.com/questions/20749819/pyqt5-failing-import-of-qtgui
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
menu.triggered.connect(self.exit)
def exit(self):
QtCore.QCoreApplication.exit()
def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
on=r''# ADD PATH OF YOUR ICON HERE .png works
main(on)
I couldn't get any of the above answers to work in PyQt5 (the exit in the system tray menu, wouldn't actually exit), but i managed to combine them for a solution that does work. I'm still trying to determine if exitAction should be used further somehow.
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
menu.triggered.connect(self.exit)
def exit(self):
QtCore.QCoreApplication.exit()
def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
on='icon.ico'
main(on)
With a pyqt5 connected event:
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
exitAction = menu.addAction("Exit")
self.setContextMenu(menu)
menu.triggered.connect(self.exit)
def exit(self):
QtCore.QCoreApplication.exit()
it can be easier
instead:
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
write:
super().__init__(self, icon, parent)
For PySide6:
in main.py:
import sys
try:
from PySide6 import QtWidgets
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import (QIcon)
from PySide6.QtCore import (QSize)
except ImportError as e:
print("no pyside6")
print("use python.exe -m pip install pyside6")
print(str(e))
exit(0)
from silnik.mytray import SystemTrayIcon
if __name__ == "__main__":
app = QApplication(sys.argv)
ico = QIcon()
ico.addFile(u":/img/brylant_64x64.png", QSize(64, 64))
ico.addFile(u":/img/brylant_16x16.png", QSize(16, 16))
ico.addFile(u":/img/brylant_32x32.png", QSize(32, 32))
ico.addFile(u":/img/brylant_48x48.png", QSize(48, 48))
ico.addFile(u":/img/brylant_128x128.png", QSize(128, 128))
app.setWindowIcon(ico)
trayIcon = silnik.mytray.SystemTrayIcon(ico)
app.tray = trayIcon
trayIcon.show()
in folder silnik
create mytray.py:
import sys
from PySide6.QtWidgets import (QSystemTrayIcon, QMenu)
from PySide6.QtCore import (QCoreApplication)
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, icon):
super().__init__()
self.setIcon(icon)
self.menu = QMenu()
self.exitAction = self.menu.addAction("Wyjście")
self.setContextMenu(self.menu)
self.exitAction.triggered.connect(self.exit)
def exit(self):
QCoreApplication.exit()

Categories