Python - data visualization widget for Pyqt5 (full code)

foreword

Homework requirements: [All have been packaged and put on the Internet, and those who are destined can pick them up if they need them]

A report (Project report on the impact of carbon neutrality on CO2 emissions in various countries in the context of global warming)

a code

Homework package: python data visualization widget.zip - Lanzuoyun

  • When I was a freshman, I forgot to record the python homework at that time after handing in the homework (uncomfortable.jpg)
  • Now that I am a junior, I suddenly found a small function I wrote before
  • So today I used pyqt5 design interface + CSS knowledge to beautify the interface and share it here
  • It took almost an afternoon, and the zero-based Xiaobai fumbled to complete it (torture~)

1. Effect display

2. Complete code

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'DataPyQt5.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

import pyqtgraph as pg
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush, QColor
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy
from PyQt5 import QtCore,QtWidgets
import pandas as pd
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("Tx-数据可视化工具")
        MainWindow.setMinimumSize(700, 500)  # 设置窗口最小尺寸限制
        MainWindow.resize(718, 733)
        MainWindow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 设置窗口大小策略

        # 设置 Qt Style Sheet,将窗口的边界设置成圆角
        MainWindow.setStyleSheet("QWidget {border-radius: 12px;}")
        # 将窗口标记成无边框窗口
        # MainWindow.setWindowFlag(Qt.FramelessWindowHint)
        # 将窗口设置为透明,否则圆角效果将无法显示
        # MainWindow.setAttribute(Qt.WA_TranslucentBackground)

        MainWindow.setStyleSheet("border-radius: 10px;\n"
                                 "background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(208, 253, 209, 255), stop:1 rgba(170, 255, 255));\n"
"")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        #---
        self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QtCore.QRect(120, 40, 461, 251))
        self.layoutWidget.setStyleSheet("background-image: url(./img/3333.jpg);\n"
                                    "background-size: center;  /* 或者 background-size: cover; */\n"
                                    "border-radius: 5px;\n"
                                    "border: 2px solid #34baea;")
        self.layoutWidget.setObjectName("layoutWidget")

        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.layoutWidget)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setObjectName("verticalLayout_2")






        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(240, 430, 91, 31))
        self.pushButton_3.setStyleSheet("QPushButton {\n"
"\n"
"    border: 2px solid #63cab6;\n"
"    color: #0000000;\n"
"    padding: 5px;\n"
"    border-radius: 8px;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: #7ad9e3;\n"
"    color: #ffffff;\n"
"} ")
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setGeometry(QtCore.QRect(360, 430, 91, 31))
        self.pushButton_4.setStyleSheet("QPushButton {\n"
"\n"
"    border: 2px solid #63cab6;\n"
"    color: #0000000;\n"
"    padding: 5px;\n"
"    border-radius: 8px;\n"
"}\n"
"\n"
"QPushButton:hover {\n"
"    background-color: #7ad9e3;\n"
"    color: #ffffff;\n"
"} ")
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(130, 320, 71, 21))
        self.pushButton.setStyleSheet("border: none;\n"
"background-color: transparent;\n"
"font: 20px;\n"
"color: #000000;\n"
"text-decoration: underline;\n"
"text-decoration:none;\n"
"font-weight:bold;")
        self.pushButton.setAutoDefault(False)
        self.pushButton.setObjectName("pushButton")
        self.textEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.textEdit_2.setGeometry(QtCore.QRect(200, 370, 349, 39))
        self.textEdit_2.setStyleSheet("border-radius: 5px;\n"
"border: 2px solid #34baea;\n"
"background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(255, 255, 255, 255));\n"
"padding-top: 7px;  /* 清除输入框的上边距 */\n"
"padding-bottom: 0px;  /* 清除输入框的下边距 */\n"
"padding-left: 5px;  /* 添加输入框的左边距 */")
        self.textEdit_2.setObjectName("textEdit_2")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(130, 380, 71, 21))
        self.pushButton_2.setStyleSheet("border: none;\n"
"background-color: transparent;\n"
"font: 20px;\n"
"color: #000000;\n"
"text-decoration: underline;\n"
"text-decoration:none;\n"
"font-weight:bold;")
        self.pushButton_2.setAutoDefault(False)
        self.pushButton_2.setObjectName("pushButton_2")
        self.textEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.textEdit_3.setGeometry(QtCore.QRect(200, 310, 349, 39))
        self.textEdit_3.setStyleSheet("border-radius: 5px;\n"
"border: 2px solid #34baea;\n"
"background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(255, 255, 255, 255), stop:1 rgba(255, 255, 255, 255));\n"
"padding-top: 7px;  /* 清除输入框的上边距 */\n"
"padding-bottom: 0px;  /* 清除输入框的下边距 */\n"
"padding-left: 5px;  /* 添加输入框的左边距 */")
        self.textEdit_3.setObjectName("textEdit_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 718, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制圆角边框
        brush = QBrush(QColor(255, 255, 255, 100))
        painter.setBrush(brush)
        painter.drawRoundedRect(0, 0, self.width(), self.height(), 12, 12)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Tx-数据可视化工具"))
        self.pushButton_3.setText(_translate("MainWindow", "确定"))
        self.pushButton_4.setText(_translate("MainWindow", "清空"))
        self.pushButton.setText(_translate("MainWindow", "国家:"))
        self.textEdit_2.setPlaceholderText(_translate("MainWindow", "请输入数据类型(1:煤炭/2:石油/3:二氧化碳)"))
        self.pushButton_2.setText(_translate("MainWindow", "类型:"))
        self.textEdit_3.setPlaceholderText(_translate("MainWindow", "请输入国家名称(例:China)"))
if __name__ == '__main__':

    def get_data_chart():

        x = None
        y = None

        country = str(ui.textEdit_3.text())
        data_type = str(ui.textEdit_2.text())

        print("数据图正在生成中!请稍等...")
        # -----------------------------------------对数据类型 进行判断
        # -----------------------------------------
        if (data_type == "1"):

            File_co2_csv = pd.read_csv(r"csv/co2.csv")  # 读取 co2 数据表格
            df_country = File_co2_csv[File_co2_csv['Entity'] == country]  # 筛选出 对应国家的数据

            x = list(df_country['Year'])  # 存放 年份
            y = list(df_country['Annual CO2 emissions (per capita)'])  # 存放 数据

        elif (data_type == "2"):
            File_coal_csv = pd.read_csv(r"csv/co2-coal.csv")  # 读取 coal 数据表格
            df_country = File_coal_csv[File_coal_csv['Entity'] == country]  # 筛选出 对应国家的数据

            x = list(df_country['Year'])  # 存放 年份
            y = list(df_country['Annual CO2 emissions from coal'])  # 存放 数据

        elif (data_type == "3"):
            File_oil_csv = pd.read_csv(r"csv/co2-oil.csv")  # 读取 oil 数据表格
            df_country = File_oil_csv[File_oil_csv['Entity'] == country]  # 筛选出 对应国家的数据

            x = list(df_country['Year'])  # 存放 年份
            y = list(df_country['Annual CO2 emissions from oil'])  # 存放 数据

        #------------------------画图

        plt = pg.PlotWidget()
        plt.plot(x, y)
        plt.showGrid(x=True, y=True)
        return plt

    def clear_layout(ui):
        # 遍历所有的子控件
        while ui.verticalLayout_2.count():
            # 获取第 0 个子控件并从布局中移除
            item = ui.verticalLayout_2.takeAt(0)
            # 获取该子控件对应的 QWidget 或 QLayout
            widget = item.widget()
            layout = item.layout()
            # 如果是 QWidget 类型,则释放该控件
            if widget:
                widget.deleteLater()
            # 如果是 QLayout 类型,则递归调用该方法移除该布局中的子控件
            elif layout:
                clear_layout(layout)

    def uart():
        clear_layout(ui)
        ui.verticalLayout_2.addWidget(get_data_chart())

    def clear_text():
        ui.textEdit_2.clear()
        ui.textEdit_3.clear()

    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.pushButton_3.clicked.connect(uart)
    ui.pushButton_4.clicked.connect(clear_text)
    sys.exit(app.exec_())

3. Study Guide

Recommend station b up and video:

PyQt-Fluent-Widgets: Fluent Design style component library based on PyQt/PySide_哔哩哔哩_bilibili

Pyqt5 dynamic reset + weather forecast_哔哩哔哩_bilibili

GUI desktop application implemented by Python+Pyside/PyQt_哔哩哔哩_bilibili

Python GUI——PySide6:

Documentation manual: Create Python GUIs with PySide2 — Simple GUIs to full apps
Introductory video: [Completed] PySide6 has been refined and brought to life, bringing you a systematic introduction to Qt_哔哩哔哩_bilibili


4. Problem record 

1. How to quickly learn and edit the pyqt interface?

If you already know the basics of PyQt5, you can quickly learn and edit the PyQt5 interface through the following steps:

  1. Use Qt Designer to design the interface: First, you can use the Qt Designer tool to design the interface, and the interface can be saved in the form of .uia file . In Qt Designer, you can add various components, such as buttons, text boxes, list boxes, etc., and set their layout and appearance. You can also set up signals and slots, so that the interaction between components can respond to user actions.

  2. .uiConvert the file to .pya file: Once you have designed the interface, you need to convert .uithe file into a Python code file for use in the program. You can convert .uithe file :

    pyuic5 -x input.ui -o output.py

    Among them, input.uiis the .uifile , output.pyand is the path of the Python code file you want to generate.

  3. Create the main program: Now, you can create the main program and use the classes in the converted .pyfile , as well as the modules and functions provided by PyQt5, to implement the logic and functions of the interface. You can import the class in .pythe file and use it as the main window or subwindow. You can then use the layout manager in the main program to lay out the widgets, set up signals and slots, and add event handlers to widgets.

  4. Debugging and running: Using IDEs such as PyCharm can greatly improve the debugging efficiency of the PyQt5 interface. You can use the debugger in the IDE to check the running status of the program and view errors and exceptions that occur in the program. Finally, you can run the program and test its functionality through the interface.

Hope the above steps can help you quickly learn and edit the PyQt5 interface. Of course, in the process of learning, it is also very important to continuously read official documents, API documents, various books and blog articles, and have a deep understanding of all aspects of PyQt5.

2. In qyqt, if you use code to beautify the window border and make it rounded, it is similar to Apple Computer UI

To beautify window borders in PyQt you can use Qt Style Sheet. Here is the sample code to achieve rounded borders:

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QBrush, QColor
from PyQt5.QtWidgets import QApplication, QWidget


class RoundedCornerWidget(QWidget):
    def __init__(self):
        super().__init__()

        # 设置窗口的标题和大小
        self.setWindowTitle("Rounded Corner Widget")
        self.setFixedSize(400, 300)

        # 设置 Qt Style Sheet,将窗口的边界设置成圆角
        self.setStyleSheet("QWidget {border-radius: 12px;}")

        # 将窗口标记成无边框窗口
        self.setWindowFlag(Qt.FramelessWindowHint)

        # 将窗口设置为透明,否则圆角效果将无法显示
        self.setAttribute(Qt.WA_TranslucentBackground)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制圆角边框
        brush = QBrush(QColor(255, 255, 255, 100))
        painter.setBrush(brush)
        painter.drawRoundedRect(0, 0, self.width(), self.height(), 12, 12)


if __name__ == "__main__":
    app = QApplication([])
    window = RoundedCornerWidget()
    window.show()
    app.exec()

In the constructor of RoundedCornerWidgetthe class , we set the title and size of the window, and then use the Qt Style Sheet to round the borders of the window. We also mark the window as a borderless window and set it to be transparent.

In paintEvent()the method , we use QPainter to draw the rounded border, and use the setRenderHint() method to enable anti-aliasing.

When using window corner rounding, you need to pay attention to setting it as transparent, otherwise the rounding effect will not be displayed. It can be achieved by setAttribute(Qt.WA_TranslucentBackground)setting the window to be transparent, or by Qt Style Sheet background-color: transparent;. The former is used in the example.

3. How to edit the CSS style sheet directly in the style editor in qyqtDesign, and change the background of the listview into a white semi-transparent rounded card?

You can edit the CSS stylesheet in the style editor to achieve this effect. Here's an example CSS stylesheet that sets the QListView's background to a translucent white card with rounded corners:

#listView {
	background-color: rgba(255, 255, 255, 0.8);
	border-radius: 10px;
	padding: 10px;
}

This assumes that the objectName property of the QListView is set to "listView". You can copy this CSS code into the style editor and apply it to your QListView control.

4. Edit the style sheet in qyqtDesign, and use css to beautify the button into a flat style

Editing style sheets in Qt Designer can be achieved in two ways:

  1. Edit CSS stylesheets directly in the style editor
  2. Set the style of widget by QWidget.setProperty() method

The following are the steps to achieve button flattening through the style editor:

  1. In Qt Designer, select the button to edit and select 表单-> from the menu bar 编辑样式表.

  2. In the style editor, paste the following CSS style code into the editing area:

    QPushButton {
        background-color: transparent;
        border: 2px solid #3498db;
        color: #3498db;
        padding: 5px;
        border-radius: 8px;
    }
    
    QPushButton:hover {
        background-color: #3498db;
        color: #ffffff;
    }
    

    The above code defines the style of the button, including: transparent background, blue solid border, blue text color, 5-pixel padding and 8-pixel rounded border. When the mouse hovers over the button, another set of styles is applied, changing the text and background colors.

  3. Click the Apply button for the changes to take effect.

  4. Save the window as .uia file and close Qt Designer.

  5. Load the UI file and display the window in a PySide6 application:

    from PySide6.QtWidgets import QApplication, QMainWindow, QWidget
    from PySide6.QtUiTools import QUiLoader
    from PySide6.QtCore import QFile
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
    
            # 加载 UI 文件
            ui_file = QFile("my_ui_file.ui")
            ui_file.open(QFile.ReadOnly)
            loader = QUiLoader()
            self.widget = loader.load(ui_file, self)
            ui_file.close()
    
            # 设置 widget 样式
            self.widget.setProperty("flat", True)  # 设置按钮为扁平化样式
    
            # 将 widget 添加到主窗口
            self.setCentralWidget(self.widget)
    
    
    if __name__ == "__main__":
        app = QApplication([])
        window = MainWindow()
        window.show()
        app.exec()
    

    The above code loads the UI file my_ui_file.uinamed and displays the widget flatwith the style attribute Trueset in the window.

Note, if you're defining changes to the global widget in your stylesheet, you can use the following code:

* {
    font-size: 14px;
    font-family: Arial;
}

This will change the font size and font of all widgets.

Guess you like

Origin blog.csdn.net/Pan_peter/article/details/130458587