PyQt5 use shortcuts in opened menu - python

In a PyQt5 application I have a QMenu. I want to make it so that once the menu is open, users can use keys 1, 2, 3, etc to select option 1, 2, 3, etc in the menu. However, I'm having trouble setting the shortcut, or getting the shortcut to react to the keypress.
I've taken an example from this website, and adapted it slightly to show my issue. I tried assigning shortcuts in the addAction function, but this does not work.
I've tried creating regular QShortcuts, but those no longer respond when the menu is open. I noticed that I can change the selected option using arrow up and down, and then confirm my selection with the enter key, so the QMenu is able to catch keypresses. But how can I assign my own shortcuts?
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Context Menu"
self.top = 200
self.left = 500
self.width = 400
self.height = 300
self.InitWindow()
def InitWindow(self):
self.setWindowIcon(QtGui.QIcon("icon.png"))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
def contextMenuEvent(self, event):
contextMenu = QMenu(self)
newAct = contextMenu.addAction("New", self.triggered, shortcut='A')
openAct = contextMenu.addAction("Open", self.triggered2, shortcut='B')
quitAct = contextMenu.addAction("Quit", self.triggered3, shortcut='C')
action = contextMenu.exec_(self.mapToGlobal(event.pos()))
if action == quitAct:
self.close()
def triggered(self):
print("triggered 1")
def triggered2(self):
print("triggered 2")
def triggered3(self):
print("triggered 3")
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

When a QMenu is opened, shortcuts are not active, but accelerator keys are working. You declare them with &:
newAct = contextMenu.addAction("New &1", self.triggered)
When the context menu pops up, pressing 1 triggers the correct function.

The QKeySequence class encapsulates a key sequence as used by shortcuts.
More... https://doc.qt.io/qt-5/qkeysequence.html
Try it:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Context Menu"
self.top = 200
self.left = 500
self.width = 400
self.height = 300
self.InitWindow()
def InitWindow(self):
self.setWindowIcon(QtGui.QIcon("icon.png"))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
def contextMenuEvent(self, event):
contextMenu = QMenu(self)
# newAct = contextMenu.addAction("New", self.triggered, shortcut='A')
newAct = contextMenu.addAction(
"New (&A)", self.triggered, shortcut=QtGui.QKeySequence.New) # +++
openAct = contextMenu.addAction(
"Open (&B)", self.triggered2, shortcut=QtGui.QKeySequence.Open) # +++
quitAct = contextMenu.addAction(
"Quit (&C)", self.triggered3, shortcut=QtGui.QKeySequence.Quit) # +++
action = contextMenu.exec_(self.mapToGlobal(event.pos()))
if action == quitAct:
self.close()
def triggered(self):
print("triggered 1")
def triggered2(self):
print("triggered 2")
def triggered3(self):
print("triggered 3")
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

Related

Bring to the front the MainWindow in Pyqt5

I am dealing with the following problem, while I am having multiple windows open, i would like to build a function linked to a button to bring to the front the Main window.
Thank you in advance.
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window 2")
self.pushButton = QPushButton("Back to window1", self)
self.pushButton.clicked.connect(self.window1)
def window1(self): # <===
pass;
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Go to window 2 ", self)
self.pushButton.move(275, 200)
self.label = QLabel("window 1", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.pushButton.clicked.connect(self.window2) # <===
def window2(self): # <===
self.w = Window2()
self.w.show()
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
#app.exec_()
exit(app.exec_())
if __name__=='__main__':
main()
Regards
I am expecting a function to call back the widget "Window"
You could emit a signal from your second window that your fist window listens for, and calls .raise_() when triggered.
Update: Added a call to activateWindow in the first windows callback. thanks #musicmante
For example:
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSignal # import signal
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QLabel)
class Window2(QMainWindow):
unfocus = pyqtSignal() # create signal
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setWindowTitle("Window 2")
self.pushButton = QPushButton("Back to window1", self)
# button press emits signal
self.pushButton.clicked.connect(self.unfocus.emit)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.pushButton = QPushButton("Go to window 2 ", self)
self.pushButton.move(275, 200)
self.label = QLabel("window 1", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.pushButton.clicked.connect(self.window2) # <===
def window2(self): # <===
self.w = Window2()
self.w.unfocus.connect(self.bring_to_top) # listen for signal and raise_ to top focus
self.w.show()
def bring_to_top(self):
self.activateWindow()
self.raise_()
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
#app.exec_()
exit(app.exec_())
if __name__=='__main__':
main()

Moving across elements using Up-Down keys

I make a program using PyQt5 and Python3.7. How to move across elements using arrow keys instead of tab key? (e.g. moving from button to textbox using down key)
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QLineEdit, QMainWindow, QPushButton, QFileSystemModel, QTreeView, \
QFileDialog, QComboBox
from PyQt5.QtCore import pyqtSlot
class App(QMainWindow):
def __init__(self):
super(App, self).__init__()
self.title = 'by Qt5 and python 3.7'
self.left = 10
self.top = 10
self.width = 1000
self.height = 500
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.label = QLabel('File Name: ')
self.label.move(20, 20)
self.btn_browse = QPushButton('Browse', self)
self.btn_browse.move(50, 20)
self.btn_browse.clicked.connect(self.on_click)
self.textbox = QLineEdit(self)
self.textbox.move(170, 20)
self.textbox.resize(280, 40)
self.page_view = QLineEdit(self)
self.page_view.move(20, 100)
self.page_view.resize(800, 400)
self.show()
#pyqtSlot()
def on_click(self):
print('PyQt5 button click')
# self.openFileNameDialog()
# self.saveFileDialog()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
One possible solution is to overwrite the keyPressEvent() method to detect the desired key and use focusNextPrevChild() by passing False or True if you want the focus to go to the previous or next widget, respectively.
from PyQt5.QtCore import pyqtSlot, Qt
class App(QMainWindow):
# ...
def keyPressEvent(self, e):
if e.key() == Qt.Key_Down:
self.focusNextPrevChild(True)
elif e.key() == Qt.Key_Up:
self.focusNextPrevChild(False)
# ...

How to print text beside Editor using PyQt5

I just started to learn how to build a GUI using PyQt5.
I trace some example on the internet and trying to create a GUI for practice.
But I have a problem when I tried to show a text next to the Editor.
I follow the way that I found on the internet but it just not working.
can anyone tell me how to fix it?
I comment the part that I am trying to show the text in my code
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import xml.etree.cElementTree as ET
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
#self.textbox.setAlignment(Qt.AlignRight)
self.textbox.move(80, 20)
self.textbox.resize(200,40)
self.textbox2 = QLineEdit(self)
self.textbox2.move(80, 80)
self.textbox2.resize(200,40)
#####################################
# the part i am trying to show text #
#####################################
txt1 = QLabel("case indes",self)
txt1.setAlignment(Qt.AlignCenter)
mytext = QFormLayout()
mytext.addRow(txt1,self.textbox) # not showing in Aligned position
mytext.addRow("Case type",tbox2) # not working
# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,150)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.center()
self.show()
#pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
textboxValue2 = self.textbox2.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue + " , second msg is: " + textboxValue2, QMessageBox.Ok, QMessageBox.Ok)
print(textboxValue)
self.textbox.setText("")
self.textbox2.setText("")
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The layouts are used to manage the position and size of the widgets so you should not use move or resize, you have never established which widget the layout belongs to and finally QMainWindow is a special widget in which you must establish a centralwidget. In the next section there is the solution:
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
central_widget = QWidget()
self.setCentralWidget(central_widget)
# Create textbox
self.textbox = QLineEdit()
self.textbox2 = QLineEdit()
txt1 = QLabel("case indes",self)
txt1.setAlignment(Qt.AlignCenter)
mytext = QFormLayout(central_widget)
mytext.addRow(txt1, self.textbox) # not showing in Aligned position
mytext.addRow("Case type", self.textbox2) # not working
# Create a button in the window
self.button = QPushButton('Show text')
mytext.addRow(self.button)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.center()
self.show()

Clear Button PyQt5

I have been trying to build a simple GUI with:
A QLineEdit where the user writes a string
A QPushButton that clears whatever the user writes in the above lineedit every time I click on it.
My issue is in the second one. I have been trying to solve it by looking at solutions online but they weren't really useful so far. Can anyone give a hint on how to proceed?
Here is my code:
import sys
from PyQt5.QtWidgets import QWidget, QLineEdit
from PyQt5.QtWidgets import QLabel, QPushButton, QApplication
from PyQt5.QtCore import pyqtSlot
app = QApplication(sys.argv)
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left = 10
self.top = 10
self.width = 800
self.height = 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.on_clickC1)
#pyqtSlot()
# Functions for the CLEAR buttons
def on_clickC1(self):
self.x1 = clearSearch1(self.textbox_index1.text(''))
return self.x1
def clearSearch1(self.x):
return self.x.clear()
if __name__ == '__main__':
app.aboutToQuit.connect(app.deleteLater)
ex = App()
sys.exit(app.exec_())
Thanks so much in advance,
Mattia
I do not understand what you are trying to do, the solution is simple, you must connect the clicked signal to the clear method directly without creating any other function:
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'MyApp'
self.left, self.top, self.width, self.height = 10, 10, 800, 800
self.initUI()
self.show()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox for index number 1
self.nameLabel = QLabel(self)
self.nameLabel.setText('Insert something:')
self.nameLabel.move(20, 80)
self.textbox_index1 = QLineEdit(self)
self.textbox_index1.move(20, 100)
self.textbox_index1.resize(280, 40)
# Create a button in the window
self.buttonC1 = QPushButton('Clear', self)
self.buttonC1.move(300, 119)
# connect buttons "CLEAR" to function
self.buttonC1.clicked.connect(self.textbox_index1.clear)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

PyQt Right click Menu for QComboBox

I'm trying to extend the QComboClass with a right click menu, and offer it an option to set the current index to -1 (clearing the selection). I'm having trouble invoking the context menu or even the right click event.
class ComboBox(QComboBox):
def __init__(self, *args, **kwargs):
super(ComboBox, self).__init__()
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showMenu)
def showMenu(self, pos):
menu = QMenu()
clear_action = menu.addAction("Clear Selection", self.clearSelection)
action = menu.exec_(self.mapToGlobal(pos))
def clearSelection(self):
self.setCurrentIndex(-1)
Could someone tell me what I'm doing wrong?
can you try this,
def showMenu(self,event):
menu = QMenu()
clear_action = menu.addAction("Clear Selection", self)
action = menu.exec_(self.mapToGlobal(event.pos()))
if action == clear_action:
self.clearSelection()
You can try this
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QMenu
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.lbl = QtGui.QLabel("Ubuntu", self)
self.combo = QtGui.QComboBox(self)
self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
self.combo.customContextMenuRequested.connect(self.showMenu)
self.combo.addItem("Ubuntu")
self.combo.addItem("Mandriva")
self.combo.addItem("Fedora")
self.combo.addItem("Red Hat")
self.combo.addItem("Gentoo")
self.combo.move(50, 50)
self.lbl.move(50, 150)
self.combo.activated[str].connect(self.onActivated)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QtGui.QComboBox')
self.show()
def showMenu(self,pos):
menu = QMenu()
clear_action = menu.addAction("Clear Selection")
action = menu.exec_(self.mapToGlobal(pos))
if action == clear_action:
self.combo.setCurrentIndex(0)
def onActivated(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

Categories