IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> 学习PyQt后的一次综合实例 -> 正文阅读

[C++知识库]学习PyQt后的一次综合实例

前言

一、目的及功能

二、步骤

????????1.使用QT designer进行图形构建

2.ui文件转py文件

3.对pyuic生成的py文件“添油加醋”

4.建立主文件,构造函数

?三.其中遇到的问题及经验

?四.结果展示



前言

? ? ? ? 从开始学习编程以来就一直想要打造一个不是命令行的gui界面,但当时只会c语言,要gui有点复杂。不过今非昔比,随着python技艺的加深,逐步可以理解使用pyQT了。

? ? ? ? 以下算是经过一段时间的学习后的综合产物了。

一、目的及功能

  1. ?构建基本的GUI界面,实现发送POST和GET请求。
  2. ?设置背景图片,透明度等。
  3. 对QT designer ,pyuic生成的代码进行二次改变

二、步骤

1.使用QT designer进行图形构建

? ? ? ? 其中过程不再赘述。

界面如下:

2.ui文件转py文件

? ? ? ? 由于编辑器使用的是VS Code ,自己配置了任务,tasks.json

      {
            "label": "PyUIC",
            "type": "shell",
            "command": "C:\\Users\\haost\\PycharmProjects\\pythonProject\\venv\\Scripts\\pyuic5.exe ${file} -o ${cwd}\\QT\\${fileBasenameNoExtension}_rc.py  -x&&py C:\\Users\\haost\\Desktop\\temp\\PY\\QT\\Form_trans.py -i ${file}",
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
   

注意其中的&&py C:\\Users\\haost\\Desktop\\temp\\PY\\QT\\Form_trans.py -i ${file}

Form_trans.py 内容后面会给到。

我的完整tasks.json内容如下:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "py --version "
        },
        {
            "label": "qt design",
            "type": "process",
            "command": "C:\\Users\\haost\\PycharmProjects\\pythonProject\\venv\\Lib\\site-packages\\qt5_applications\\Qt\\bin\\designer.exe"
        },
        {
            "label": "PyUIC",
            "type": "shell",
            "command": "C:\\Users\\haost\\PycharmProjects\\pythonProject\\venv\\Scripts\\pyuic5.exe ${file} -o ${cwd}\\QT\\${fileBasenameNoExtension}_rc.py  -x&&py C:\\Users\\haost\\Desktop\\temp\\PY\\QT\\Form_trans.py -i ${file}",
            "problemMatcher": [],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "label": "Pyinstaller",
            "type": "shell",
            "command": "C:\\Users\\haost\\AppData\\Local\\Programs\\Python\\Python38\\Scripts\\pyinstaller.exe -w -F ${file}"
        }
    ]
    
}

3.对pyuic生成的py文件“添油加醋”

?Form_trans.py 内容如下

#2021.7.21 @haostart
import os
import sys
import re
import argparse


# 构建命令行参数并解析

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--source", required=True)
ap.add_argument("-s", "--space", required=False)
ap.add_argument("-o", "--output", required=False)
args = vars(ap.parse_args())

print(args)


a = args['source'][:-3] + '_rc.py'
with open(a, 'r', encoding='utf-8') as f:
    # content = f.readlines()
    # print(content)
    con = f.read()
    print(re.findall(r'resize.*', con))
    con = con.replace('class Ui_Form(object)',
                      'from PyQt5.QtGui import QPixmap, QPainter\nimport sys,os,random\nclass Ui_Form(QtWidgets.QWidget)')
    con = con.replace('.retranslateUi(Form)',
                      '.retranslateUi(Form)\n        Form.paintEngine()')
    con = con.replace(re.findall(r'resize.*', con)[0], 'resize(1200,800)')
    with open(a[:-3] + '_trans.py', 'w', encoding='utf-8') as m:
        m.write(con)
    # m.close()
    # print(con)
f.close()

?????????就是对生成的py文件多引入了一些类,改变了窗口。省掉了重复性劳动。大家可以根据需要添加些固定的东西。

最后图形界面函数http_tcp_gui_rc_trans.py 如下

# -*- coding: utf-8 -*-
#2021.7.21 @haostart
# Form implementation generated from reading ui file 'c:\Users\haost\Desktop\temp\PY\QT\http_tcp_gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# 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.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets


from PyQt5 import QtCore, QtGui, QtWidgets


from PyQt5.QtGui import QPixmap, QPainter


from PyQt5.QtGui import QPixmap, QPainter


class Ui_Form(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1200, 800)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout(Form)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setSpacing(1)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setContentsMargins(-1, -1, 0, -1)
        self.horizontalLayout_2.setSpacing(0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.comboBox = QtWidgets.QComboBox(Form)
        self.comboBox.setInsertPolicy(QtWidgets.QComboBox.InsertAtBottom)
        self.comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
        self.comboBox.setIconSize(QtCore.QSize(3, 16))
        self.comboBox.setDuplicatesEnabled(False)
        self.comboBox.setObjectName("comboBox")

        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.horizontalLayout_2.addWidget(self.comboBox)
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setText("")
        self.lineEdit.setCursorPosition(0)
        self.lineEdit.setClearButtonEnabled(False)
        self.lineEdit.setObjectName("lineEdit")
        # self.comboBox.setStyleSheet(
        #     "background:transparent;border-width:0;border-style:outset")
        self.horizontalLayout_2.addWidget(self.lineEdit)
        self.verticalLayout_3.addLayout(self.horizontalLayout_2)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.verticalLayout_5 = QtWidgets.QVBoxLayout()
        self.verticalLayout_5.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label = QtWidgets.QLabel(Form)
        self.label.setObjectName("label")
        # self.label.setStyleSheet(
        #     "background:transparent;border-width:0;border-style:outset")
        self.horizontalLayout_3.addWidget(self.label)
        self.lineEdit_2 = QtWidgets.QLineEdit(Form)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.horizontalLayout_3.addWidget(self.lineEdit_2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setContentsMargins(13, -1, -1, -1)
        self.horizontalLayout_4.setSpacing(0)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setObjectName("label_2")
        # self.label_2.setStyleSheet(
        #     "background:transparent;border-width:0;border-style:outset")
        self.horizontalLayout_4.addWidget(self.label_2)
        self.lineEdit_3 = QtWidgets.QLineEdit(Form)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.horizontalLayout_4.addWidget(self.lineEdit_3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_4)
        self.verticalLayout_5.addLayout(self.verticalLayout_2)
        self.add_sure = QtWidgets.QPushButton(Form)
        self.add_sure.setObjectName("add_sure")
        self.verticalLayout_5.addWidget(self.add_sure)
        self.verticalLayout.addLayout(self.verticalLayout_5)
        self.tableWidget = QtWidgets.QTableWidget(Form)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setWindowOpacity(0.5)
        self.tableWidget.setStyleSheet(
            "background-color:rgba(244,244,244,100);border-width:0;border-style:outset")
        # self.tableWidget.setStyleSheet(
        #     "background:transparent;border-width:0;border-style:outset")
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(True)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        font.setKerning(True)
        item.setFont(font)
        self.tableWidget.setColumnWidth(0, 210)
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(True)
        font.setWeight(75)
        item.setFont(font)
        self.tableWidget.setColumnWidth(1, 250)
        self.tableWidget.setHorizontalHeaderItem(1, item)
        self.verticalLayout.addWidget(self.tableWidget)
        self.verticalLayout_3.addLayout(self.verticalLayout)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.textBrowser = QtWidgets.QTextBrowser(Form)
        self.textBrowser.setObjectName("textBrowser")
        self.tableWidget.setWindowOpacity(0.5)
        self.textBrowser.setStyleSheet(
            "background-color:rgba(244,244,244,100);border-width:0;border-style:outset")
        self.horizontalLayout.addWidget(self.textBrowser)
        self.verticalLayout_4.addLayout(self.horizontalLayout)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setSizeConstraint(
            QtWidgets.QLayout.SetFixedSize)
        self.horizontalLayout_6.setContentsMargins(80, 5, 80, 5)
        self.horizontalLayout_6.setSpacing(30)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.send = QtWidgets.QPushButton(Form)
        self.send.setCheckable(False)
        self.send.setObjectName("send")
        self.horizontalLayout_6.addWidget(self.send)
        self.exit = QtWidgets.QPushButton(Form)
        self.exit.setAutoDefault(False)
        self.exit.setObjectName("exit")
        self.horizontalLayout_6.addWidget(self.exit)
        self.verticalLayout_4.addLayout(self.horizontalLayout_6)

        self.retranslateUi(Form)
        Form.paintEngine()

        QtCore.QMetaObject.connectSlotsByName(Form)
        # self.paintEvent(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.comboBox.setItemText(0, _translate("Form", "POST"))
        self.comboBox.setItemText(1, _translate("Form", "GET"))
        self.lineEdit.setPlaceholderText(_translate("Form", "请输入host地址"))
        self.label.setText(_translate("Form", "名称:"))
        self.label_2.setText(_translate("Form", "值:"))
        self.add_sure.setText(_translate("Form", "确定添加"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("Form", "data名称"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("Form", "值"))
        self.send.setText(_translate("Form", "发送"))
        self.send.setShortcut(_translate("Form", "Return"))
        self.exit.setText(_translate("Form", "退出"))
        self.exit.clicked.connect(Form.exit)
        self.send.clicked.connect(Form.send)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

4.建立主文件,构造函数

????????

#2021.7.21 @haostart
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
from PyQt5.QtCore import QSize, Qt, QPoint



import json
import sys
import os
import pprint
import requests
import urllib
import urllib.request

from http_tcp_gui_rc_trans import Ui_Form

from PyQt5.QtGui import QPixmap, QPainter, QBrush, QColor


class MainWindow(QWidget):
    def paintEvent(self, e):

        self.painter = QPainter()
        self.painter.begin(self)
        self.painter.setRenderHint(QPainter.Antialiasing)

        rect = self.rect()

        self.pixmap = QPixmap("gelin1.png").scaled(rect.size()) #背景图片,自己改

        self.painter.drawPixmap(rect, self.pixmap)

        self.painter.end()

    def mousePressEvent(self, event):

        if (event.button() == QtCore.Qt.LeftButton):
            self.m_startPoint = self.frameGeometry().topLeft() - event.globalPos()

    def mouseMoveEvent(self, event):

        # / * 移动窗口 * /
        self.move(event.globalPos() + self.m_startPoint)

    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        # 使用ui文件导入定义界面类
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        # self.setWindowState(QtCore.Qt.WindowMaximized)

        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)  # 设置无边框窗口
        self.setAttribute(Qt.WA_TranslucentBackground)  # 设置背景透明
        # self.setStyleSheet(
        #     "border-radius: 15px;")
        self.data = {}
        self.ui.textBrowser.setFontPointSize(40)
        self.ui.textBrowser.setText('@Haostart')
        # self.paintEngine()

    def exit(self) -> bool:
        return super().close()

    def jsonDataToUrlParams(self, params_data):
        url_str = '?'
        nums = 0
        max_nums = len(params_data)
        for key in params_data:
            nums = nums + 1
            # 如果是最后一位就不要带上&
            # 拼为url字符串
            if nums == max_nums:
                url_str += str(key) + '=' + str(params_data[key])
            else:
                url_str += str(key) + '=' + str(params_data[key]) + '&'
        return url_str

    def get(self):
        print('get')
        host = self.ui.lineEdit.text()
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
        data = self.data
        host = host + self.jsonDataToUrlParams(data)
        response = requests.get(host, headers=headers)
        content = response.content.decode('utf-8')
        content_text = response.text
        print(content)

        self.ui.textBrowser.setText(content_text)

    def post(self):

        host = self.ui.lineEdit.text()
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
        response = requests.post(host, headers=headers, data=self.data)
        content = response.content.decode('utf-8')
        content_text = response.text
        print(content)

        self.ui.textBrowser.setText(content_text)

    def send(self):
        cur_choose = self.ui.comboBox.currentText()
        if cur_choose == 'POST':
            self.post()
        elif cur_choose == 'GET':
            self.get()

    def add(self):
        data_name = self.ui.lineEdit_2.text()
        data_val = self.ui.lineEdit_3.text()
        if data_name != '':
            self.ui.table.insertRow(0)
            self.ui.item = QtWidgets.QTableWidgetItem()
            # self.ui.font = QtGui.QFont()
            # self.ui.font.setPointSize(8)
            # self.ui.font.setBold(True)
            # self.ui.font.setWeight(75)
            # self.ui.item.setFont(self.ui.font)

            self.ui.item.setText(data_name)
            self.ui.tableWidget.setItem(0, 0, self.ui.item)
            self.ui.item = QtWidgets.QTableWidgetItem()
            self.ui.item.setText(data_val)
            self.ui.tableWidget.setItem(0, 1, self.ui.item)

            # self.data.setdefault(self.ui.lineEdit_2.text(),
            #                      self.ui.lineEdit_3.text())
            self.data[data_name] = data_val
        print(self.data)
        # self.data_json = json.loads(self.data)

    def delr(self):
        try:
            data_name = self.ui.table.item(
                self.ui.table.currentRow(), 0).text()
            self.data.pop(data_name)
            # print(data_name)
            print(self.data)
            self.ui.table.removeRow(self.ui.table.currentRow())
        except:
            print('error')


if __name__ == "__main__":

    app = QApplication(sys.argv)
    Form = MainWindow()

    Form.show()
    sys.exit(app.exec_())

如此,一个有背景图片的gui界面诞生了,其中控件使用了setStyleSheet可以设置透明样式。

self.label.setStyleSheet("background:transparent;border-width:0;border-style:outset")

三.其中遇到的问题及经验

1.关于布局方面研究了一下

2.关于qt生成的图形文件和自己建立的主文件之间如何调用

3.对class类的理解更深入

4.如何设置背景图片,透明度,窗口圆角等

5.对qt各类控件的使用自然更加熟练了

四.结果展示

?圆角是PS的、、、因为窗口背景设置成了透明,所以直接显示图片。

很遗憾无法让普通图片圆角显示(我做不到)

关于post和get功能,可以在主文件里更改。

  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2021-07-24 23:54:43  更:2021-07-24 23:55:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 9:18:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码