Created
March 14, 2018 17:54
-
-
Save ghalter/23703699d8eaf98947c242ee427cdbb9 to your computer and use it in GitHub Desktop.
Basic PyQt Signal Slot Example with PyQT5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PyQt5.QtCore import * | |
from PyQt5.QtWidgets import * | |
from PyQt5.QtGui import * | |
import sys | |
from functools import partial | |
class MainWindow(QMainWindow): | |
onNameEntered = pyqtSignal(str) | |
def __init__(self): | |
super(MainWindow, self).__init__() | |
self.inner = QWidget(self) | |
self.inner.setLayout(QVBoxLayout(self)) | |
self.line_edit = QLineEdit(self) | |
self.text_plot = TextPlot(self) | |
self.lbl_has_been_clicked = QLabel("Has not been clicked, yet", self) | |
self.inner.layout().addWidget(self.line_edit) | |
self.inner.layout().addWidget(self.text_plot) | |
self.inner.layout().addWidget(self.lbl_has_been_clicked) | |
self.setCentralWidget(self.inner) | |
# Connecting the Signals and Slots | |
self.line_edit.editingFinished.connect(self.parse_name) | |
self.onNameEntered.connect(self.text_plot.update_plot) | |
# You can also use partial to set the parameter when connecting slots | |
self.text_plot.hasBeenClicked.connect(partial(self.on_plot_clicked, "has been clicked")) | |
self.show() | |
@pyqtSlot() | |
def parse_name(self): | |
name = self.line_edit.text() | |
name = "Input: " + name | |
#Emit the Signal to the TextPlot | |
self.onNameEntered.emit(name) | |
@pyqtSlot(str) | |
def on_plot_clicked(self, text): | |
self.lbl_has_been_clicked.setText(text) | |
class TextPlot(QGraphicsView): | |
hasBeenClicked = pyqtSignal() | |
def __init__(self, parent): | |
super(TextPlot, self).__init__(parent) | |
self.setScene(QGraphicsScene(self)) | |
@pyqtSlot(str) | |
def update_plot(self, text): | |
self.scene().clear() | |
for i in range(10): | |
itm = self.scene().addText(text) | |
itm.setDefaultTextColor(QColor(200,100,100,200)) | |
itm.setPos(10, i * 20) | |
def mousePressEvent(self, event: QMouseEvent): | |
self.hasBeenClicked.emit() | |
# The QT Exception Hook | |
def my_exception_hook(exctype, value, traceback): | |
# Print the error and traceback | |
print((exctype, value, traceback)) | |
# Call the normal Exception hook after | |
sys._excepthook(exctype, value, traceback) | |
sys.exit(1) | |
if __name__ == '__main__': | |
sys._excepthook = sys.excepthook | |
sys.excepthook = my_exception_hook | |
app = QApplication(sys.argv) | |
main = MainWindow() | |
sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment