analitics

Pages

Saturday, June 10, 2017

Python Qt4 - part 001.

Today I started with PyQt4 and python version :
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
To install PyQt4 I used this link to take the executable named: PyQt4-4.11.4-gpl-Py2.7-Qt4.8.7-x32.exe.
The name of this executable shows us: can be used with python 2.7.x versions and come with Qt4.8.7 for our 32-bit python.
I start with a default Example class to make a calculator interface with PyQt4.
This is my example:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui

"""
Qt.Gui calculator example
"""

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):
 title = QtGui.QLabel('Title')
        titleEdit = QtGui.QLineEdit()
        grid = QtGui.QGridLayout()
 grid.setSpacing(10)

 grid.addWidget(title, 0, 0)

 grid.addWidget(titleEdit,0,1,1,4)

        self.setLayout(grid)
 
        names = ['Cls', 'Bck', 'OFF',
                 '/', '.', '7', '8',
                '9', '*', 'SQR', '3',
                 '4', '5', '-', '=',
                '0', '1', '2', '+']
        
        positions = [(i,j) for i in range(1,5) for j in range(0,5)]
        
        for position, name in zip(positions, names):
            
            if name == '':
                continue
            button = QtGui.QPushButton(name)
            grid.addWidget(button, *position)
            
        self.move(300, 250)
        self.setWindowTitle('Calculator')
        self.show()
        
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
The example is simple.
First, you need a QGridLayout - this makes a matrix.
I used labels, line edit and buttons all from QtGui: QLabel, QLineEdit and QPushButton.
First into this matrix - named grid is Title and edit area named titleEdit.
This two is added to the grid - matrix with addWidget.
The next step is to put all the buttons into one array.
This array will be added to the grid matrix with a for a loop.
To make this add from array to matrix I used the zip function.
The zip function makes an iterator that aggregates elements from each of the iterable.
Also, I set the title to Calculator with setWindowTitle.
I have not implemented the part of the events and the calculation.
The main function will start the interface by using the QApplication.
The goal of this tutorial was the realization of the graphical interface with PyQt4.
This is the result of my example: