An Introduce to PyQT Button Bind Click Event with Examples – PyQT Tutorial

By | December 13, 2019

Button is a widely used widget in pyqt, we can bind a click event on it. How to bind? To answer this problem, we will introduce you how to do in this tutorial.

Create a button

First, we should create a button using pyqt.

from PyQt5.QtWidgets import QApplication, QWidget,QPushButton, QHBoxLayout, QVBoxLayout
from PyQt5.QtWidgets import QLineEdit, QMessageBox
from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem, QHeaderView
from PyQt5 import QtCore

btn_search = QPushButton('Find', self)

Code above is an example demo. To understand self, you should view this tutorial.

Understand PyQT QHBoxLayout addStretch() with Examples for Beginners

Bind a click event for button

To bind a click event, we can use this way:

button.clicked.connect(function)

where button is pyqt QPushButton widget, function is a name of function.

Here is an example:

btn_search.clicked.connect(self.on_file_search)

In this code, we make btn_search button bind a click event on_file_search.

Define on_file_search() function

To process button click event, we should define on_file_search() function. Here is an example:

    def on_file_search(self):
        #get text
        text = self.keyedit.text()
        reply = QMessageBox.information(self,'Text',text, QMessageBox.Ok | QMessageBox.Close, QMessageBox.Close)

on_file_search() will show a dialog to display a text you have entered in a QLineEdit.

Then, when you input a text in a QLineEdit, click button btn_search. The text will be displayed. The effect likes:

pyqt button bind click event examples

Leave a Reply

Your email address will not be published. Required fields are marked *