使用PyQt5开发一个GUI程序的实例演示

embedded/2024/11/30 8:09:49/

一、安装Python

下载安装到这个目录
G:\Python38-32
安装完成有这些工具,后面备用:
G:\Python38-32\Scripts\pyrcc5.exe
G:\Python38-32\Scripts\pyuic5.exe

二、PyQt环境配置

pip install PyQt5
pip install pyqt5-tools

建议使用国内源,进行快速安装:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyqt5
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyqt5-tools


安装QT,安装到 E:\Qt5.12.6 目录下;

从这个目录下打开qtcreator.exe 
E:\Qt5.12.6\Tools\QtCreator\bin
 


三、用QTCreator设计界面
Qt Designer 是通过拖拽的方式放置控件,并实时查看控件效果进行快速UI设计。

这里只需要 MainWindow.ui 文件

最终生成.ui文件(实质上是XML格式的文件),可以通过pyuic5工具转换成.py文件。


ui文件到 py文件:pyuic5.exe xxx.ui -o xxx.py

pyuic5.exe主要是把Qt Designer生成的.ui文件换成.py文件。

pyrcc5.exe主要是把编写的.qrc资源文件换成.py文件。

需要把按钮事件绑定到槽函数:
self.pushButton.clicked.connect(self.PropertyClicked)

完成后的代码如下

testMVCam.py

python">import sys  
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QMainWindow
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import mvsdk
from MainWindow import Ui_MainWindow color = Falseclass MyWidget(QMainWindow, Ui_MainWindow):  def __init__(self, parent=None):  super(MyWidget, self).__init__(parent)  self.setupUi(self)  # 枚举相机DevList = mvsdk.CameraEnumerateDevice()nDev = len(DevList)if nDev < 1:print("No camera was found!")returnfor i, DevInfo in enumerate(DevList):print("{}: {} {}".format(i, DevInfo.GetFriendlyName(), DevInfo.GetPortType()))i = 0 if nDev == 1 else int(input("Select camera: "))DevInfo = DevList[i]print(DevInfo)# 打开相机global hCamera# hCamera = 0try:hCamera = mvsdk.CameraInit(DevInfo, -1, -1)except mvsdk.CameraException as e:print("CameraInit Failed({}): {}".format(e.error_code, e.message))QMessageBox.question(self, '本程序', '初始化相机失败!')returnglobal capcap = mvsdk.CameraGetCapability(hCamera)if  cap.sIspCapacity.bMonoSensor:mvsdk.CameraSetIspOutFormat(hCamera, mvsdk.CAMERA_MEDIA_TYPE_MONO8)color = Falseelse:mvsdk.CameraSetIspOutFormat(hCamera, mvsdk.CAMERA_MEDIA_TYPE_RGB8)color = True# 相机模式切换成连续采集mvsdk.CameraSetTriggerMode(hCamera, 0)# 自动曝光# mvsdk.CameraSetAeState(hCamera, 1)mvsdk.CameraCreateSettingPage(hCamera, 0, DevInfo.acFriendlyName, 0, 0, 0)# 让SDK内部取图线程开始工作mvsdk.CameraPlay(hCamera)# Mindvision线程self.MVthread = MindvisionThread()self.MVthread.signal.connect(self.image_callback)self.MVthread.start()self.pushButton.clicked.connect(self.PropertyClicked)#self.pushButton_9.clicked.connect(self.save_mindvision_image)def stop_thread(self):if self.MVthread is not None and self.MVthread.isRunning():self.MVthread.stop()def save_mindvision_image(self):global hCamerapRawData, FrameHead = mvsdk.CameraGetImageBuffer(hCamera, 2000)mvsdk.CameraImageProcess(hCamera, pRawData, pFrameBuffer, FrameHead)mvsdk.CameraReleaseImageBuffer(hCamera, pRawData)mvsdk.CameraSaveImage(hCamera, "./pic.bmp", pFrameBuffer, FrameHead, mvsdk.FILE_BMP, 80)def image_callback(self, image):pixmap = QPixmap.fromImage(image)# ratio = max(width / self.left_bottom_image.width(), height / self.left_bottom_image.height())self.label.setAlignment(Qt.AlignCenter)self.label.setScaledContents(True)self.label.setPixmap(pixmap)def PropertyClicked(self):mvsdk.CameraShowSettingPage(hCamera, True);		# def initUI(self):  # # 创建标签  # label = QLabel('Hello, PyQt!')  # # 创建按钮  # button = QPushButton('Click me!')  # button.clicked.connect(self.buttonClicked)  # # 将标签和按钮添加到窗口中  # self.setCentralWidget(label)  # self.setWidget(button)  # def buttonClicked(self):  # # 在这里编写按钮被点击时要执行的代码  # print('Button clicked!')  
# 程序退出def closeEvent(self, event):reply = QMessageBox.question(self, '本程序', '是否要退出?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)if reply == QMessageBox.Yes:global pFrameBufferevent.accept()self.stop_thread()mvsdk.CameraUnInit(hCamera)mvsdk.CameraAlignFree(pFrameBuffer)sys.exit(0)else:event.ignore()		class MindvisionThread(QThread):signal = pyqtSignal(QImage)def __init__(self):super(MindvisionThread, self).__init__()self.is_running = True# 计算RGB buffer所需的大小,这里直接按照相机的最大分辨率来分配FrameBufferSize = cap.sResolutionRange.iWidthMax * cap.sResolutionRange.iHeightMax * 3		global pFrameBufferpFrameBuffer = mvsdk.CameraAlignMalloc(FrameBufferSize, 16)		def run(self):while self.is_running:global capglobal hCameraglobal FrameHead# 分配RGB buffer,用来存放ISP输出的图像#global pFrameBuffer#pFrameBuffer = mvsdk.CameraAlignMalloc(FrameBufferSize, 16)try:pRawData, FrameHead = mvsdk.CameraGetImageBuffer(hCamera, 2000)mvsdk.CameraImageProcess(hCamera, pRawData, pFrameBuffer, FrameHead)# Windows 上下帧翻转mvsdk.CameraFlipFrameBuffer(pFrameBuffer, FrameHead, 1)mvsdk.CameraReleaseImageBuffer(hCamera, pRawData)# mvsdk.CameraSaveImage(hCamera, ".\\pic.bmp", pFrameBuffer, FrameHead, mvsdk.FILE_BMP, 80)# break#mat = QImage(pFrameBuffer, cap.sResolutionRange.iWidthMax, cap.sResolutionRange.iHeightMax, QImage.Format_RGB888 if True == color else QImage.Format_Indexed8 )if FrameHead.uiMediaType==mvsdk.CAMERA_MEDIA_TYPE_MONO8:#if(quit) breakimg = QImage(pFrameBuffer, FrameHead.iWidth, FrameHead.iHeight, QImage.Format_Indexed8)#img.setColorTable(grayColourTable);#emit captured(img);self.signal.emit(QImage(img))else:#if(quit) breakimg = QImage(pFrameBuffer, FrameHead.iWidth,  FrameHead.iHeight, QImage.Format_RGB888)#emit captured(img);self.signal.emit(QImage(img))# self.signal.emit(QImage(mat))n = self.getTrgNum()# print( n )except mvsdk.CameraException as e:print("CameraGetImageBuffer failed({}): {}".format(e.error_code, e.message) )def stop(self):self.is_running = Falsedef getTrgNum(self):global hCamerac_Num = mvsdk.c_int()mvsdk.CameraSpecialControl(hCamera, 0x1000, 0x1000050C, mvsdk.addressof(c_Num))return c_Num.value		if __name__ == '__main__':  app = QApplication(sys.argv)  widget = MyWidget()  widget.show()  sys.exit(app.exec_())

MainWindow.py

python"># -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# 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, QtWidgetsclass Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(800, 600)self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setObjectName("centralwidget")self.pushButton = QtWidgets.QPushButton(self.centralwidget)self.pushButton.setGeometry(QtCore.QRect(20, 20, 75, 23))self.pushButton.setObjectName("pushButton")self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)self.pushButton_2.setGeometry(QtCore.QRect(120, 20, 75, 23))self.pushButton_2.setObjectName("pushButton_2")self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)self.pushButton_3.setGeometry(QtCore.QRect(220, 20, 75, 23))self.pushButton_3.setObjectName("pushButton_3")self.label = QtWidgets.QLabel(self.centralwidget)self.label.setGeometry(QtCore.QRect(20, 60, 551, 421))self.label.setObjectName("label")MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))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 retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))self.pushButton.setText(_translate("MainWindow", "属性设置"))self.pushButton_2.setText(_translate("MainWindow", "PushButton"))self.pushButton_3.setText(_translate("MainWindow", "PushButton"))self.label.setText(_translate("MainWindow", "TextLabel"))

运行效果

(结束)


http://www.ppmy.cn/embedded/141689.html

相关文章

随机变量的线性最小均方估计(LMMSE)——多个观测变量

假设有一个随机变量 x x x需要估计&#xff0c;目标是找到一个线性估计器 x ^ ∑ i 0 N − 1 a i y i b \hat{x} \sum_{i0}^{N-1} a_i y_i b x^∑i0N−1​ai​yi​b&#xff0c;使得估计误差 e x − x ^ e x - \hat{x} ex−x^的均方误差 E [ e 2 ] E[e^2] E[e2]最小。 …

记一次 .NET某hdp智能柜系统 卡死分析

一&#xff1a;背景 1. 讲故事 停了一个月时间没有更新博客了&#xff0c;主要是这段时间有些许事情导致心神不宁&#xff0c;我这个人也比较浮躁所以无法潜心修炼&#xff0c;事情如下&#xff1a; 被狗咬了 也不知道是不是出门没看黄历&#xff0c;在小区门口店里买烟&am…

uniapp实现轮播图结构数据渲染

实现轮播图结构数据渲染 swiper swiper | uni-app官网 (dcloud.net.cn) 滑块视图容器。【设计人员应以375px的宽度设计小程序】 一般用于左右滑动或上下滑动&#xff0c;比如banner轮播图。 组件代码 <swiper indicator-dots circular><swiper-item v-for"i…

HTML 画布:网页上的创意绘图板

HTML 画布:网页上的创意绘图板 HTML5的画布(Canvas)元素为网页开发者提供了一种在网页上绘制图形和动画的强大工具。它是HTML5标准的一部分,被设计为允许脚本语言(通常是JavaScript)动态渲染图形、图像和动画。在这篇文章中,我们将深入探讨HTML画布的各个方面,包括其基…

【Docker】部署nginx

docker部署nginx docker部署nginx镜像加速器1、拉取nginx镜像2、创建nginx容器3、浏览器访问 docker部署nginx 镜像加速器 备注&#xff1a;阿里云镜像加速地址 https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors可用的镜像源&#xff1a; https://https://reg…

Spring MVC 深度剖析:优势与劣势全面解读

文章目录 Spring MVC 优势1. **松耦合**2. **易于测试**3. **灵活性**4. **强大的配置机制**5. **异常处理**6. **国际化支持**7. **数据验证**8. **安全性**9. **性能优化** Spring MVC 劣势1. **学习曲线**2. **配置复杂性**3. **性能开销**4. **视图技术限制**5. **社区和支…

微信小程序Webview与H5通信

背景 近期有个微信小程序需要用到web-view嵌套H5的场景&#xff0c;该应用场景需要小程序中频繁传递数据到H5进行渲染&#xff0c;且需要保证页面不刷新。 由于微信小程序与H5之间的通信限制比较大&#xff0c;显然无法满足于我的业务场景 探索 由于微信小程序与webview的环境是…