How to implement a simple button in PyQt

47,270

If you're new to PyQt, there are some useful tutorials on the PyQt Wiki to get you started. But in the meantime, here's your "Hello World" example:

from PyQt5 import QtWidgets, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.button = QtWidgets.QPushButton('Test')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        print('Hello World')

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())
Share:
47,270
Abid Rahman K
Author by

Abid Rahman K

"I prefer my application crashing than getting wrong answers." Contact me at [email protected] Visit my blog : http://opencvpython.blogspot.com/ Visit : Remove Convexity Defects of a Sudoku Square Visit : http://stackoverflow.com/questions/9413216/simple-digit-recognition-ocr-in-opencv-python Visit : Simple watershed sample in OpenCV-Python

Updated on January 01, 2022

Comments

  • Abid Rahman K
    Abid Rahman K over 2 years

    I want to implement a simple button in PyQt which prints "Hello world" when clicked. How can I do that?

    I am a real newbie in PyQt.

  • Amelio Vazquez-Reina
    Amelio Vazquez-Reina about 11 years
    When I try this I get: Failed to load platform plugin "xcb". Available platforms are "linuxfb" and "minimal". Do you know why? I am running from with the latest stable Python, IPython, Qt5 and snapshot from PyQt4
  • ekhumoro
    ekhumoro about 11 years
    @user815423426. Sounds like your installation is broken. What platform are you on, and how did you install the components?