Reputation: 946
I am try to make a keyboard shortcut to exit the application after a Critical message pops up. i would like to make the user press the keyboard shortcut then be prompted with a Critical Message and after they click yes it will exit the program. ive been trying for a while now and couldnt get it to work. here is what i have
here is my code
import sys
import webbrowser
import random
import time
import os
import subprocess
from PyQt4.QtCore import QSize, QTimer
from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, QWidget, QIcon, QLabel, QPainter, QPixmap, QMessageBox, \
QAction, QKeySequence
def CloseSC(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
class MainWindow(QMainWindow, ):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(50, 50, 400, 450)
self.setFixedSize(400, 450)
self.startUIWindow()
self.actionExit = QAction(('E&xit'), self)
self.actionExit.setShortcut(QKeySequence("Ctrl+Q"))
self.actionExit.triggered.connect(CloseSC)
Upvotes: 0
Views: 1697
Reputation: 243897
You must be add action to widget with {your widget}.addAction({your action})
This is my solution:
import sys
from PyQt4.QtGui import QMainWindow, QMessageBox, QAction, QKeySequence, QApplication
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setGeometry(50, 50, 400, 450)
self.setFixedSize(400, 450)
self.actionExit = QAction(('E&xit'), self)
self.actionExit.setShortcut(QKeySequence("Ctrl+Q"))
self.addAction(self.actionExit)
self.actionExit.triggered.connect(self.CloseSC)
def CloseSC(self):
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Critical)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
if msg.exec_() == QMessageBox.Ok:
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
After Ctrl+Q
Upvotes: 1