Thursday, March 31, 2022

Plotting Realtime Data using Matplotlib in PyQt6

 This demo program shows how to plot realtime data, specifiy the location on a window among other things.


The Output:



The Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import sys
import numpy as np
from matplotlib.backends.qt_compat import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure

def onclick(event):
    global clicks
    clicks.append(event.xdata)

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(ApplicationWindow, self).__init__()
        
        dynamic_canvas = FigureCanvas(Figure(figsize=(5, 3), dpi=115))
        dynamic_canvas.setParent(self)
        dynamic_canvas.move(25,25)
        self._dynamic_ax = dynamic_canvas.figure.subplots()
        dynamic_canvas.figure.canvas.mpl_connect('button_press_event', onclick)
        self._dynamic_ax.grid()
        self._timer = dynamic_canvas.new_timer(
            100, [(self._update_window, (), {})])
        self._timer.start()

        button_stop = QtWidgets.QPushButton('Stop', self)
        button_stop.setGeometry(625, 95, 100, 40)
        button_stop.clicked.connect(self._timer.stop)

        button_start = QtWidgets.QPushButton('Start', self)
        button_start.setGeometry(625, 40, 100, 40)
        button_start.clicked.connect(self._timer.start)
 
        
        self.setGeometry(25, 45, 745, 400)
        self.setWindowTitle('Post 8')
        self.show()

    def _update_window(self):
        self._dynamic_ax.clear()
        global x, y1, y2, y3, N, count_iter, last_number_clicks
        x.append(x[count_iter] + 0.01)
        y1.append(np.random.random())
        idx_inf = max([count_iter-N, 0])
        if last_number_clicks < len(clicks):
            for new_click in clicks[last_number_clicks:(len(clicks))]:
                rowPosition = self.table_clicks.rowCount()
                self.table_clicks.insertRow(rowPosition)
                self.table_clicks.setItem(rowPosition,0, QtWidgets.QTableWidgetItem(str(new_click)))
                self.table_clicks.setItem(rowPosition,1, QtWidgets.QTableWidgetItem("Descripcion"))
            last_number_clicks = len(clicks)
        self._dynamic_ax.plot(x[idx_inf:count_iter], y1[idx_inf:count_iter],'-o', color='b')
        count_iter += 1
        self._dynamic_ax.figure.canvas.draw()
#%%
if __name__ == "__main__":
    pressed_key = {}
    clicks = []
    last_number_clicks = len(clicks)
    N = 25
    y1 = [np.random.random()]
    x = [0]
    count_iter = 0
    qapp = QtWidgets.QApplication(sys.argv)
    app = ApplicationWindow()
    app.show()
    sys.exit(qapp.exec())

Tuesday, March 29, 2022

Tabbed Container with PyQt6

 This demo program show how to create a tab widget, place it on a specific location in a window, add widgets to each tab among others.

The output:



The code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.tab1 = QWidget()
        self.tab2 = QWidget()

        label1 = QLabel("Widget in Tab 1.")
        label2 = QLabel("Widget in Tab 2.")
        label3 = QLabel("Test Widget in Tab 1.")
        label4 = QLabel("Test Widget in Tab 2.")
        self.tabwidget = QTabWidget(self)
        self.tabwidget.addTab(self.tab1,"Tab 1")
        self.tabwidget.addTab(self.tab2,"Tab 2")
        layout = QFormLayout()
        layout.addRow(label1)
        layout.addRow(label3)
        self.tab1.setLayout(layout)
        layout1 = QFormLayout()
        layout1.addRow(label2)
        layout1.addRow(label4)
        self.tab2.setLayout(layout1)

        self.tabwidget.setGeometry(25, 25, 350, 260)
        self.setGeometry(300, 300, 490,300)

app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec())

Matplotlib with PyQt6

 This demo program shows how to plot line graph, place it on a specific location in a window, specify the size, among others.


The output:



The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sys
from PyQt6.QtWidgets import QApplication,  QWidget
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt


class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        m = PlotCanvas(self, width=5, height=3)
        m.move(25,25)
        
 

        self.setGeometry(25, 45, 625, 400)
        self.setWindowTitle('Post 6')
        self.show()
        
                 
class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=3, dpi=115):
        fig = Figure(figsize=(width, height), dpi=dpi)
 

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)
        self.plot()


    def plot(self):
        x = [0, 0, 25, 22, 0, 0, 0, 50, 78, 260, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        z = [0, 0, 75, 42, 0, 0, 0, 150, 165, 400, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        a = [0, 0, 1005, 72, 0, 0, 0, 350, 350, 650, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
        ax = self.figure.add_subplot(111)
        ax.plot(y,x)
        ax.plot(y,z)
        ax.plot(y,a)
        self.draw()
        
def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Progressbar with PyQt6

This demo program shows how to create a progressbar, set its color, align text, place it to a specific location in a window, among other things.

Output:



The Code:

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import sys
import time
from PyQt6.QtWidgets import QApplication,  QWidget, QPushButton, QProgressBar
from PyQt6.QtCore import Qt

TIME_LIMIT = 100

class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        self.progress = QProgressBar(self)
        self.progress.setGeometry(25, 35, 305, 20)
        self.progress.setMaximum(100)
        self.progress.setStyleSheet("QProgressBar::chunk "
                          "{"
                          "background-color: red;text-align: center"
                          "}")
        self.progress.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        pb3 = QPushButton('Process', self)
        pb3.setGeometry(50, 100, 250, 30)
        pb3.setStyleSheet('QPushButton {background-color: #2F569B; color: #d4d4d4;}')
        pb3.clicked.connect(self.onClick_pb3)

        self.setGeometry(25, 45, 350, 150)
        self.setWindowTitle('Post 5')
        self.show()
        
 
    def onClick_pb3(self):
 
       count = 0
       while count < TIME_LIMIT:
            count += 1
            time.sleep(0.01)
            self.progress.setValue(count)
                

def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Datagrid with PyQt6

This demo program shows how to create a datagrid, place it on a specific location in a window, among other things. Output:
The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import sys
from PyQt6.QtWidgets import QApplication,  QWidget,  QTableWidget
from PyQt6.QtGui import  QPainter, QColor, QPen
from PyQt6.QtCore import Qt

class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):


        self.setGeometry(25, 45, 330, 325)
        self.setWindowTitle('Post 4')
        self.createTable()
        self.show()
        
 
    def createTable(self):
        self.tableWidget = QTableWidget(self)
        self.tableWidget.setRowCount(24)
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setFixedSize(280, 275)
        self.tableWidget.move(25, 25)
        self.tableWidget.setHorizontalHeaderLabels(['PM2.5', 'PM10'])
        self.tableWidget.horizontalHeader().setStretchLastSection(True)
        self.tableWidget.verticalHeader().setStretchLastSection(True)

 
def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Draw Rectangle and Ellipse with PyQt6

This demo program shows how to draw rectangle and ellipse and place at specific location on the window, specify fill colors, set size and pen size.

Output:


The code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import sys
from PyQt6.QtWidgets import QApplication,  QWidget,  QLabel
from PyQt6.QtGui import  QPainter, QColor, QPen
from PyQt6.QtCore import Qt

class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):


        self.setGeometry(25, 45, 640, 300)
        self.setWindowTitle('Post 3')
        self.show()
        
 
    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()
           
    
    def drawRectangles(self, qp):

        color = QColor(0, 0, 0)
        color.setNamedColor('#d4d4d4')
        qp.setPen(color)

        qp.setBrush(QColor('#ffffff'))
        qp.drawRect(25, 25, 150, 30)

        pen = QPen()
        pen.setWidth(5)
        qp.setBrush(QColor('#00aa00'))
        qp.drawEllipse(25, 80, 300, 150)

        qp.setBrush(QColor('#d4d4d4'))
        qp.drawEllipse(40, 115, 270, 110)


        ii = 0
        while ii < 24:
            ii = ii + 1
            iii = (ii * 24) + 10
            qp.setBrush(QColor('#00aa00'))
            qp.drawRect(iii, 260, 22, 15)

 
def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Label with PyQt6

 This sample program demonstrate how to format a label, place it on a specific location in the window and try to specify font, size, alignment, among others.

Output:



The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import sys
from PyQt6.QtWidgets import QApplication,  QWidget,  QLabel
from PyQt6.QtGui import   QFont
from PyQt6.QtCore import Qt

class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        lbl1a =  QLabel('RECS', self)
        lbl1a.setGeometry(25, 10, 50, 35)
        lbl1a.setStyleSheet('QLabel {background-color: #0E95A6; color: #d4d4d4;}')
        lbl1a.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        lbl17 =  QLabel('24Hr Air Quality', self)
        lbl17.setGeometry(25, 55, 150, 35)
        
        lbl19 =  QLabel('Air Quality Analysis Dash Board', self)
        lbl19.setFont(QFont("Arial", 18))
        lbl19.setGeometry(25, 100, 350, 40)

        self.setGeometry(25, 45, 380, 150)
        self.setWindowTitle('Post 2')
        self.show()
        
  
def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

Button with PyQt6

This sample program demonstrate how to format a button, place it on a specific location in the window and try to execute a command upon pressing.

Output:


The code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import sys
import os
from PyQt6.QtWidgets import QApplication,  QWidget, QPushButton

class Window(QWidget):

    def __init__(self):
        super(Window, self).__init__()

        self.initUI()

    def initUI(self):

        pb1 = QPushButton('Exit', self)
        pb1.setGeometry(50, 20, 250, 30)
        pb1.setStyleSheet('QPushButton {background-color: #2F569B; color: #d4d4d4;}')
        pb1.clicked.connect(onClick_pb1)
        
        pb2 = QPushButton('Click Me!', self)
        pb2.setGeometry(50, 60, 250, 30)
        pb2.setStyleSheet('QPushButton {background-color: #2F569B; color: #d4d4d4;}')
        pb2.clicked.connect(self.onClick_pb2)
        
        pb3 = QPushButton('Open Notepad', self)
        pb3.setGeometry(50, 100, 250, 30)
        pb3.setStyleSheet('QPushButton {background-color: #2F569B; color: #d4d4d4;}')
        pb3.clicked.connect(onClick_pb3)

        self.setGeometry(25, 45, 350, 150)
        self.setWindowTitle('Post 1')
        self.show()
        
 
    def onClick_pb2(self):
 
       print("clicked")
       
 
        
def onClick_pb3():
    os.popen(r"C:\WINDOWS\system32\notepad.exe")


    
def onClick_pb1():
    exit()

def main():

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()