import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Analysis
Function arguments in Python
In Python, user-defined functions can take four different types of arguments.
Function definition
def defaultArg( name, msg = "Hello!"):
Function call
defaultArg( name)
Function definition
def requiredArg (str,num):
Function call:
requiredArg ("Hello",12)
Function definition
def keywordArg( name, role ):
Function call
keywordArg( name = "Tom", role = "Manager")
or
keywordArg( role = "Manager", name = "Tom")
Function definition
def varlengthArgs(*varargs):
Function call
varlengthArgs(30,40,50,60)
class Example(QWidget):
def __init__(self):
super().__init__()
...
Three important things in object oriented programming are classes, data, and methods. Here we create a new class called Example
. The Example
class inherits from the QWidget
class. This means that we call two constructors: the first one for the Example
class and the second one for the inherited class. The super()
method returns the parent object of the Example
class and we call its constructor. The self
variable refers to the object itself.
Why have we used __init__
?
Check this out:
class A(object):
def __init__(self):
self.lst = []
class B(object):
lst = []
and now try:
>>> x = B()
>>> y = B()
>>> x.lst.append(1)
>>> y.lst.append(2)
>>> x.lst
[1, 2]
>>> x.lst is y.lst
True
and this:
>>> x = A()
>>> y = A()
>>> x.lst.append(1)
>>> y.lst.append(2)
>>> x.lst
[1]
>>> x.lst is y.lst
False
Does this mean that x in class B is established before instantiation?
Yes, it's a class attribute (it is shared between instances). While in class A it's an instance attribute.
self.initUI()
The creation of the GUI is delegated to the initUI()
method.
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
All three methods have been inherited from the QWidget
class. The setGeometry()
does two things: it locates the window on the screen and sets it size. The first two parameters are the x and y positions of the window. The third is the width and the fourth is the height of the window. In fact, it combines the resize()
and move()
methods in one method. The last method sets the application icon. To do this, we have created a QIcon
object. The QIcon
receives the path to our icon to be displayed.
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
The application and example objects are created. The main loop is started.