Call function by Enter key - python

How can I make (on_click) works when QPushButton ("click") is pressed by Enter keyboard key? it only interacts with mouse_click
import sys
from PyQt5.QtWidgets import *
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.label = QLabel("",self)
self.label.move(100, 100)
self.button = QPushButton('click', self)
self.button.move(100, 50)
self.button.clicked.connect(self.on_click)
self.setGeometry(500, 150, 200, 200)
self.show()
def on_click(self):
self.label.setText("Hello")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

You have to overwrite the keyPressEvent method:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.label = QLabel("",self)
self.label.move(100, 100)
self.button = QPushButton('click', self)
self.button.move(100, 50)
self.button.clicked.connect(self.on_click)
self.setGeometry(500, 150, 200, 200)
self.show()
def on_click(self):
self.label.setText("Hello")
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
self.on_click()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

I found a solution regarding this: keyPressEvent() method doesn't work for PyQt5 / Python 3+.
You need to override the function in super class.
MainWindow.keyPressEvent = self.keyPressEvent

Related

How to activate Key Press Event, in Pyqt5?

Here is my Code. I want to capture a pressed key and print it. But Nothing will Happen, How to resolve it? I Have two classes. One is Create_Instance and another one is Main_Window. In My code, I have Only Lable items to display. How to activate it?
Edited
import sys
from PyQt5.QtWidgets import *
class Create_Instance(QWidget):
def __init__(self,dict_item):
super().__init__()
self.dict_items = dict_item
self.lbl = QLabel("This is My Label")
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.lbl)
self.setLayout(self.vbox)
def keyPressEvent(self, event):
print(event)
print(self.dict_items)
class Main_Window(QWidget):
def __init__(self):
super(). __init__()
self.setWindowTitle("Main Window")
self.layout_main = QHBoxLayout()
self.firstmenu_container = Create_Instance(dict_item="1")
self.secondmenu_container = Create_Instance(dict_item="2")
self.layout_main.addWidget(self.firstmenu_container)
self.layout_main.addWidget(self.secondmenu_container)
self.setLayout(self.layout_main)
def main():
app = QApplication(sys.argv)
ex = Main_Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You must add the widget to the layout:
def __init__(self):
super().__init__()
self.setWindowTitle("Main Window")
self.layout_main = QHBoxLayout()
self.firstmenu_container = Create_Instance(dict_item="1")
self.layout_main.addWidget(self.firstmenu_container)
self.secondmenu_container = Create_Instance(dict_item="2")
self.layout_main.addWidget(self.secondmenu_container)
self.setLayout(self.layout_main)

PyQt5 Switch between window after time in a loop

i use the code below, found on stackoverflow. i want to build a loop which getting started with a button on the main window. After clicked window2 should open for 30 seconds. then window3 should open for 30 seconds. then window2 should open and so on.
i make a slide methode but it wont work.
i try it with the window2() and window3() and slide() methode
what is my target?
i want a slideshow with the two window(window2 & window3) that alternate.
not more but it is an endless loop
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window22222")
class Window3(QMainWindow): # <===
def __init__(self):
super().__init__()
self.setWindowTitle("Window333333")
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("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(self.slide)
self.main_window()
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
def window2(self): # <===
self.w2 = Window2()
self.w2.show()
time.sleep(5)
self.w3 = Window3()
self.w3.show()
self.w2.hide()
self.window3()
#self.hide()
def window3(self): # <===
self.w3 = Window3()
self.w3.show()
time.sleep(5)
self.w2 = Window2()
self.w2.show()
self.w3.hide()
self.window2()
#self.hide()
def slide(self):
print ("slide")
self.window2()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())
Try it:
import sys
#import time
from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
QToolTip, QMessageBox, QLabel)
class Window2(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 22222")
class Window3(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Window 333333")
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "First Window"
self.top, self.left, self.width, self.height = 100, 100, 680, 500
self.flag = ...
self.pushButton = QPushButton("Start", self)
self.pushButton.move(275, 200)
self.pushButton.setToolTip("<h3>Start the Session</h3>")
self.pushButton.clicked.connect(lambda: self.start_slide(True)) #(self.window2)
self.pushButton1 = QPushButton("Start", self)
self.pushButton1.move(20, 20)
self.pushButton1.setToolTip("<h3>Start the Session</h3>")
self.pushButton1.clicked.connect(lambda: self.start_slide(False))
# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
self.main_window()
self.w2 = Window2()
self.w3 = Window3()
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.viewWindows)
def start_slide(self, flag):
self.timer.stop()
self.w3.hide()
self.w2.hide()
if flag: self.w2.show()
else: self.w3.show()
self.flag = not flag
self.timer.start(5000)
def viewWindows(self):
if self.flag:
self.w2.show()
self.w3.hide()
else:
self.w3.show()
self.w2.hide()
self.flag = not self.flag
def closeEvent(self, event):
self.w2.close()
self.w3.close()
self.close()
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
def main_window(self):
self.label = QLabel("Manager", self)
self.label.move(285, 175)
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

show text after enter key pressed

I want show text after enter key pressed
from PyQt5.QtWidgets import QWidget, QApplication, QPlainTextEdit, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt
import sys
class PlainTextEdit(QPlainTextEdit):
def __init__(self, parent):
super().__init__(parent=parent)
close_window = ClosingWindow()
vbox = QVBoxLayout()
self.close_window.setLayout(vbox)
def keyPressEvent(self, QKeyEvent):
if QKeyEvent.key() == Qt.Key_Enter:
self.close_window.label_display.setText("Enter key pressed")
class ClosingWindow(QWidget):
def __init__(self):
super().__init__()
plainText = PlainTextEdit(self)
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
label_display = QLabel("Text Here")
self.setLayout(vbox)
self.setWindowTitle("Message Box")
self.setGeometry(200, 200, 500, 300)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
close_win = ClosingWindow()
sys.exit(app.exec_())
Your code has the following errors:
You are creating an infinite loop: You are creating a PlainTextEdit within a ClosingWindow, and in that PlainTextEdit you are creating another ClosingWindow, and in that other ClosingWindow you are creating a PlainTextEdit, etc. Every time you use the constructor of a class you are creating a different object, so the "close_window" created in PlainTextEdit is different from the "close_win".
Each class must have a single responsibility (1), in your case the responsibility of PlainTextEdit is to notify that it was pressed enter, and in that case you must use a signal.
The enter key on the keyboard does not correspond to Qt::Key_Enter but Qt::Key_Return, it only corresponds to Qt::Key_Return on the keypad.
It is not necessary to create a layout in PlainTextEdit.
Considering the above, the solution is:
from PyQt5 import QtCore, QtWidgets
class PlainTextEdit(QtWidgets.QPlainTextEdit):
sendTextSignal = QtCore.pyqtSignal(str)
def keyPressEvent(self, event):
if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.sendTextSignal.emit("Enter key pressed")
else:
self.sendTextSignal.emit("Not Enter key pressed")
super().keyPressEvent(event)
class ClosingWindow(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
plainText = PlainTextEdit()
label_display = QtWidgets.QLabel("Text Here")
plainText.sendTextSignal.connect(label_display.setText)
vbox = QtWidgets.QVBoxLayout(self)
vbox.addWidget(plainText)
vbox.addWidget(label_display)
self.setWindowTitle("Message Box")
self.setGeometry(200, 200, 500, 300)
self.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
close_win = ClosingWindow()
sys.exit(app.exec_())
(1) Single responsibility principle

PyQt4 - Open *.py file when Button is clicked

I want to open/run a *.py file with pythonw.exe, when the Start-Button is clicked. Can anyone tell me how this works? I havent found the right function anywhere.
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
btn1 = QtGui.QPushButton('Start', self)
# OPENFILE SOMEHOW!!
btn1.resize(btn1.sizeHint())
btn1.move(20, 20)
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.move(150, 20)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Python Script')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You can use subprocess.call. For example, this code runs external.py , when the Start is clicked:
import sys
from PyQt4 import QtGui, QtCore
import subprocess
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def run(self, path):
subprocess.call(['pythonw',path])
def initUI(self):
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
btn1 = QtGui.QPushButton('Start', self)
btn1.resize(btn1.sizeHint())
btn1.move(20, 20)
btn1.clicked.connect(lambda:self.run('external.py'))
qbtn = QtGui.QPushButton('Quit', self)
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.resize(qbtn.sizeHint())
qbtn.move(150, 20)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Python Script')
#subprocess.call(['pythonw','3.py'])
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

PyQt class inheritance

I am having troubles to understand class inheritance with Python/PyQt. I have a MainWindow and a Popup QWidget. I want to interact with the self.label1 of the MainWindow after the QWidget was opened in a pop up window but I don't know how to do it. I know only the other way around, to reach all widgets from the popup Window inside MainWindow but not vice versa.
Here is an example, self.label1 of MainWindow should get another text after MyPopup opens in a new window:
import sys
from PyQt4.Qt import *
class MyPopup(QWidget):
def __init__(self):
QWidget.__init__(self)
# I want to change the lable1 of MainWindow
self.cw.label1.setText('hello')
class MainWindow(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.cw = QWidget(self)
self.setCentralWidget(self.cw)
self.btn1 = QPushButton("Click me", self.cw)
self.btn1.setGeometry(QRect(50, 50, 100, 30))
self.label1 = QLabel("No Commands running", self.cw)
self.connect(self.btn1, SIGNAL("clicked()"), self.doit)
self.w = None
def doit(self):
self.w = MyPopup()
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
You need to pass the main window as a parameter to the constructor of MyPopup, try this:
import sys
from PyQt4.Qt import *
class MyPopup(QWidget):
def __init__(self, mainWindow):
QWidget.__init__(self)
# use the mainWindow passed as parameter
mainWindow.label1.setText('hello')
class MainWindow(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.cw = QWidget(self)
self.setCentralWidget(self.cw)
self.btn1 = QPushButton("Click me", self.cw)
self.btn1.setGeometry(QRect(50, 50, 100, 30))
self.label1 = QLabel("No Commands running", self.cw)
self.connect(self.btn1, SIGNAL("clicked()"), self.doit)
self.w = None
def doit(self):
self.w = MyPopup(self) #when creating the popup pass in the main window
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
This is the prior answer from Alvaro Fuentes, with the minor updates necessary for PyQt5.
import sys
from PyQt5.Qt import *
class MyPopup(QWidget):
def __init__(self, mainwin):
QWidget.__init__(self)
# I want to change the lable1 of MainWindow
mainwin.label1.setText('hello')
class MainWindow(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.cw = QWidget(self)
self.setCentralWidget(self.cw)
self.btn1 = QPushButton("Click me", self.cw)
self.btn1.setGeometry(QRect(50, 50, 100, 30))
self.label1 = QLabel("No Commands running", self.cw)
self.btn1.clicked.connect(self.doit)
self.w = None
def doit(self):
self.w = MyPopup(self)
self.w.setGeometry(QRect(100, 100, 400, 200))
self.w.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())

Categories