analitics

Pages

Wednesday, November 7, 2018

Python Qt5 : QLCDNumber and QDial example.

This tutorial uses a simple example of QLCDNumber and QDial.
The steps start with create the QWidget with the QLCDNumber and QDial.
You need to set geometry for both and connect the dial with valueChanged.
Finally you need to use show to see the QWidget.
The result is show into the next screenshot:

Let see the source code:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QWidget, QLCDNumber, QDial, QApplication)

class QLCDNumber_QDial(QWidget):
    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        the_lcd = QLCDNumber(self)
        the_dial = QDial(self)

        self.setGeometry(150, 100, 220, 100)
        self.setWindowTitle('QLCDNumber')

        the_lcd.setGeometry(10,10,70,70)
        the_dial.setGeometry(140,10,70,70)

        the_dial.valueChanged.connect(the_lcd.display)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    run = QLCDNumber_QDial() 
    sys.exit(app.exec_())

Tuesday, November 6, 2018

Python Qt5 : QColorDialog example.

Today I will show you how to use the QColorDialog and clipboard with PyQt5.
You can read documentation from the official website.
This example used a tray icon with actions for each type of code color.
The code of color is put into clipboard area and print on the shell.
I use two ways to get the code of color:
  • parse the result of currentColor depends by type of color codel;
  • get the code of color by a special function from QColorDialog;
To select the color I want to use is need to use the QColorDialog:

Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# create the application
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

# get the icon file
icon = QIcon("icon.png")

# create clipboard
clipboard = QApplication.clipboard()
# create dialog color
dialog = QColorDialog()

# create functions to get parsing color
def get_color_hex():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText(color.name())
        print(clipboard.text())

def get_color_rgb():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("rgb(%d, %d, %d)" % (
            color.red(), color.green(), color.blue()
        ))
        print(clipboard.text())

def get_color_hsv():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("hsv(%d, %d, %d)" % (
            color.hue(), color.saturation(), color.value()
        ))
        print(clipboard.text())
# create function to use getCmyk 
def get_color_getCmyk():
    if dialog.exec_():
        color = dialog.currentColor()
        clipboard.setText("Cmyk(%d, %d, %d, %d, %d)" % (
            color.getCmyk()
        ))
        print(clipboard.text())


# create the tray icon application
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)

# create the menu and add actions
menu = QMenu()
action1 = QAction("Hex")
action1.triggered.connect(get_color_hex)
menu.addAction(action1)

action2 = QAction("RGB")
action2.triggered.connect(get_color_rgb)
menu.addAction(action2)

action3 = QAction("HSV")
action3.triggered.connect(get_color_hsv)
menu.addAction(action3)

action4 = QAction("Cmyk")
action4.triggered.connect(get_color_getCmyk)
menu.addAction(action4)

action5 =QAction("Exit")
action5.triggered.connect(exit)
menu.addAction(action5)

# add the menu to the tray icon application
tray.setContextMenu(menu)

app.exec_()

Monday, November 5, 2018

Python Qt5 : tray icon example.

This tutorial is about another tray icon application type.
The base application is the same like any application with some changes with this steps:
- QSystemTrayIcon this will start to create the application like an tray icon application;
- create one menu to show if you use the right click of mouse;
- add a menu with action items;
- add the exit action to close the tray icon application;
- you can use the action item from menu to print a message
Let's see the source code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# create the application
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

# create the icon
icon = QIcon("icon.png")

# create the tray icon 
tray = QSystemTrayIcon()
tray.setIcon(icon)
tray.setVisible(True)

# this will print a message 
def print_msg():
 print("This action is triggered connect!")

# create the menu for tray icon
menu = QMenu()

# add one item to menu 
action = QAction("This is menu item")
menu.addAction(action)
action.triggered.connect(print_msg)

# add exit item to menu 
exitAction = QAction("&Exit")
menu.addAction(exitAction)
exitAction.triggered.connect(exit)

# add the menu to the tray
tray.setContextMenu(menu)

# start application execution 
app.exec_()
This is result of the running source code:

Sunday, November 4, 2018

Python Qt5 : QtSql with QtOpenGL example.

Today I will show you how to deal with QtOpenGL.
Let's make a test to see what is this:
>>> import PyQt5
>>> from PyQt5.QtOpenGL import *
>>> dir(PyQt5.QtOpenGL)
['QGL', 'QGLContext', 'QGLFormat', 'QGLWidget', '__doc__', '__file__', '__loader
__', '__name__', '__package__', '__spec__']
The QtOpenGL is used to take an OpenGL content and show into the PyQt5 application.
You need to kknow how to use OpenGL API.
You can see the result of this example:

This is the source code for my example:
import sys
import math

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtOpenGL import QGL, QGLFormat, QGLWidget

try:
    from OpenGL import GL
except ImportError:
    app = QApplication(sys.argv)
    QMessageBox.critical(None, "OpenGL samplebuffers",
            "PyOpenGL must be installed to run this example.")
    sys.exit(1)

# use to create OpenGL content 
class GLWidget(QGLWidget):
    GL_MULTISAMPLE = 0x809D
    # rotation to 0
    rot = 0.0

    def __init__(self, parent):
        super(GLWidget, self).__init__(QGLFormat(QGL.SampleBuffers), parent)
        self.list_ = []
        self.startTimer(40)
        self.setWindowTitle("OpenGL with sample buffers")

    def initializeGL(self):
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GL.glOrtho( -.5, .5, .5, -.5, -1000, 1000)
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()
        GL.glClearColor(1.0, 1.0, 1.0, 1.0)

        self.makeObject()

    def resizeGL(self, w, h):
        GL.glViewport(0, 0, w, h)

    def paintGL(self):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glPushMatrix()
        GL.glEnable(GLWidget.GL_MULTISAMPLE)
        GL.glTranslatef( -0.25, -0.10, 0.0)
        GL.glScalef(0.75, 1.15, 0.0)
        GL.glRotatef(GLWidget.rot, 0.0, 0.0, 1.0)
        GL.glCallList(self.list_)
        GL.glPopMatrix()

        GL.glPushMatrix()
        GL.glDisable(GLWidget.GL_MULTISAMPLE)
        GL.glTranslatef(0.25, -0.10, 0.0)
        GL.glScalef(0.75, 1.15, 0.0)
        GL.glRotatef(GLWidget.rot, 0.0, 0.0, 1.0)
        GL.glCallList(self.list_)
        GL.glPopMatrix()

        GLWidget.rot += 0.2

        self.qglColor(Qt.black)
        self.renderText(-0.35, 0.4, 0.0, "Multisampling enabled")
        self.renderText(0.15, 0.4, 0.0, "Multisampling disabled")

    def timerEvent(self, event):
        self.update()
    # create one object 
    def makeObject(self):
        x1 = +0.05
        y1 = +0.25
        x2 = +0.15
        y2 = +0.21
        x3 = -0.25
        y3 = +0.2
        x4 = -0.1  
        y4 = +0.2
        x5 = +0.25 
        y5 = -0.05

        self.list_ = GL.glGenLists(1)
        GL.glNewList(self.list_, GL.GL_COMPILE)
        
        self.qglColor(Qt.blue)
        self.geometry(GL.GL_POLYGON, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5)
        
        GL.glEndList()
    # create geometry of object depend of render - GL_POLYGON
    # used five points 
    def geometry(self, primitive, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5):
        GL.glBegin(primitive)

        GL.glVertex2d(x1, y1)
        GL.glVertex2d(x2, y2)
        GL.glVertex2d(x3, y3)
        GL.glVertex2d(x4, y4)
        GL.glVertex2d(x5, y5)

        GL.glEnd()
# start the application 
if __name__ == '__main__':

    app = QApplication(sys.argv)

    my_format = QGLFormat.defaultFormat()
    my_format.setSampleBuffers(True)
    QGLFormat.setDefaultFormat(my_format)

    if not QGLFormat.hasOpenGL():
        QMessageBox.information(None, "OpenGL using samplebuffers",
                "This system does not support OpenGL.")
        sys.exit(0)

    widget = GLWidget(None)

    if not widget.format().sampleBuffers():
        QMessageBox.information(None, "OpenGL using samplebuffers",
                "This system does not have sample buffer support.")
        sys.exit(0)

    widget.resize(640, 480)
    widget.show()

    sys.exit(app.exec_())

Saturday, November 3, 2018

Python Qt5 : QtSql with QSQLITE example.

Today I will show you how to deal with QtSql and QSQLITE and show a table into an MDI (Multiple Document Interface) application.
First I create tree scripts named:
  • PyQt5_connection.py - create a memory database and add value into table;
  • PyQt5_view.py - create a model for the table;
  • PyQt5_show.py - show the MDI application with the model table database;
The source code is commented and is simple to understand.
Let's see this python scripts:
First is PyQt5_connection.py:
from PyQt5 import QtWidgets, QtSql
from PyQt5.QtSql import *

def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        QtWidgets.QMessageBox.critical(None, "Cannot open memory database",
                             "Unable to establish a database connection.\n\n"
                             "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel)
        return False
    query = QtSql.QSqlQuery()
    #print (os.listdir("."))
    query.exec("DROP TABLE IF EXISTS Websites")
    query.exec("CREATE TABLE Websites (ID INTEGER PRIMARY KEY NOT NULL, " +     "website VARCHAR(20))")
    query.exec("INSERT INTO Websites (website) VALUES('python-catalin.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('catalin-festila.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('free-tutorials.org')")
    query.exec("INSERT INTO Websites (website) VALUES('graphic-3d.blogspot.com')")
    query.exec("INSERT INTO Websites (website) VALUES('pygame-catalin.blogspot.com')")
    return True
The next is the PyQt5_view.py python script with the model of the table from database:
from PyQt5 import QtWidgets, QtSql

from PyQt5 import QtWidgets, QtSql

class WebsitesWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(WebsitesWidget, self).__init__(parent)
 # this layout_box can be used if you need more widgets 
 # I used just one named WebsitesWidget
        layout_box = QtWidgets.QVBoxLayout(self)
 #
        my_view = QtWidgets.QTableView()
 # put viwe in layout_box area
        layout_box.addWidget(my_view)
 # create a table model
        my_model = QtSql.QSqlTableModel(self)
        my_model.setTable("Websites")
        my_model.select()
 #show the view with model  
        my_view.setModel(my_model)
        my_view.setItemDelegate(QtSql.QSqlRelationalDelegate(my_view))
The last python script named PyQt5_show.py will create the MDI application and will show databese table:
from PyQt5 import QtWidgets, QtSql
from PyQt5_connection import createConnection
# this will import any classes from PyQt5_view script
from PyQt5_view import WebsitesWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.MDI = QtWidgets.QMdiArea()
        self.setCentralWidget(self.MDI)

        SubWindow1 = QtWidgets.QMdiSubWindow()
        SubWindow1.setWidget(WebsitesWidget())
        self.MDI.addSubWindow(SubWindow1)
        SubWindow1.show()
 # you can add more widgest 
        #SubWindow2 = QtWidgets.QMdiSubWindow()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    if not createConnection():
        print("not connect")
        sys.exit(-1)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
This is the result of the running PyQt5_show.py python script:

Thursday, November 1, 2018

Python Qt5 : QtWebEngine example.

The QtWebEngine is the new web rendering engine that is planned to replace QtWebKit in Qt.
The official website tells us:
QtWebEngineWidgets or QtWebEngine libraries, depending on application type
Let's test this web rendering engine with a simple source code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication
# use the QtWebEngineWidgets
from PyQt5.QtWebEngineWidgets import *
# start my_app
my_app = QApplication(sys.argv)
# open webpage
my_web = QWebEngineView()
my_web.load(QUrl("http://free-tutorials.org"))
my_web.show()
# sys exit function
sys.exit(my_app.exec_())
The output of this running source code.