PyQt5 - Hello World


Advertisements

Creating a simple GUI application using PyQt involves the following steps −

  • Import QtCore, QtGui and QtWidgets modules from PyQt5 package.

  • Create an application object of QApplication class.

  • A QWidget object creates top level window. Add QLabel object in it.

  • Set the caption of label as "hello world".

  • Define the size and position of window by setGeometry() method.

  • Enter the mainloop of application by app.exec_() method.

Following is the code to execute Hello World program in PyQt −

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def window():
   app = QApplication(sys.argv)
   w = QWidget()
   b = QLabel(w)
   b.setText("Hello World!")
   w.setGeometry(100,100,200,50)
   b.move(50,20)
   w.setWindowTitle("PyQt5")
   w.show()
   sys.exit(app.exec_())
if __name__ == '__main__':
   window()

The above code produces the following output −

Hello World

It is also possible to develop an object oriented solution of the above code.

  • Import QtCore, QtGui and QtWidgets modules from PyQt5 package.

  • Create an application object of QApplication class.

  • Declare window class based on QWidget class

  • Add a QLabel object and set the caption of label as "hello world".

  • Define the size and position of window by setGeometry() method.

  • Enter the mainloop of application by app.exec_() method.

Following is the complete code of the object oriented solution −

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class window(QWidget):
   def __init__(self, parent = None):
      super(window, self).__init__(parent)
      self.resize(200,50)
      self.setWindowTitle("PyQt5")
      self.label = QLabel(self)
      self.label.setText("Hello World")
      font = QFont()
      font.setFamily("Arial")
      font.setPointSize(16)
      self.label.setFont(font)
      self.label.move(50,20)
def main():
   app = QApplication(sys.argv)
   ex = window()
   ex.show()
   sys.exit(app.exec_())
if __name__ == '__main__':
   main()
Hello Worlds
Advertisements