当前位置: 首页 > article >正文

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

一、安装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

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 = False

class 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!")
            return
			
        for 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 = 0
        try:
            hCamera = mvsdk.CameraInit(DevInfo, -1, -1)
        except mvsdk.CameraException as e:
            print("CameraInit Failed({}): {}".format(e.error_code, e.message))
            QMessageBox.question(self, '本程序', '初始化相机失败!')
            return
        global cap
        cap = mvsdk.CameraGetCapability(hCamera)

        if  cap.sIspCapacity.bMonoSensor:
            mvsdk.CameraSetIspOutFormat(hCamera, mvsdk.CAMERA_MEDIA_TYPE_MONO8)
            color = False
        else:
            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 hCamera
        pRawData, 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 pFrameBuffer
            event.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 pFrameBuffer
        pFrameBuffer = mvsdk.CameraAlignMalloc(FrameBufferSize, 16)		
    def run(self):
        while self.is_running:
            global cap
            global hCamera
            global 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) break
                    img = QImage(pFrameBuffer, FrameHead.iWidth, FrameHead.iHeight, QImage.Format_Indexed8)
                    #img.setColorTable(grayColourTable);
                    #emit captured(img);
                    self.signal.emit(QImage(img))

                else:
                    #if(quit) break
                    img = 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 = False
    def getTrgNum(self):
        global hCamera
        c_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

# -*- 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, QtWidgets


class 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.translate
        MainWindow.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.kler.cn/a/416854.html

相关文章:

  • 如何在Spark中使用gbdt模型分布式预测
  • 工作中Linux 内核的链表算法的使用
  • 成都睿明智科技有限公司抖音电商服务的新引擎
  • 03.ES7 04.ES8
  • 从0在自己机器上部署AlphaFold 3
  • C语言进阶7:程序环境与预处理
  • 解决“磁盘已插上,但Windows系统无法识别“问题
  • 记一次 .NET某hdp智能柜系统 卡死分析
  • el-selet下拉菜单自定义内容,下拉内容样式类似表格
  • ChatGPT的应用场景:开启无限可能的大门
  • apache实现绑定多个虚拟主机访问服务
  • Vue项目运行步骤(详细图解)
  • 静态页面 和 动态页面(Java Web开发)
  • 【Linux网络编程】第三弹---UDP网络通信深度解析:构建服务器端、客户端,并实现两端通信的完整步骤与测试
  • 【传感器技术】第6章 压电式传感器
  • [python脚本处理文件入门]-18.使用Python进行PDF文件的合并与拆分
  • 浅谈volatile
  • Mybatis:CRUD数据操作之修改数据update
  • 【QT/MinGW/.a->.lib】如何将一个用QT的MingGW编译dll项目出的dll文件导出一份.lib文件给其他项目链接动态库用
  • docker启动容器,语句名词解释
  • day21:jumpserver配置与搭建
  • 【bug】AttributeError: module ‘openai‘ has no attribute ‘error’
  • 第6章 元素应用CSS
  • 信息与网络安全笔记2
  • 常见靶场的搭建
  • 去中心化物理基础设施网络(DePIN):重塑未来的基石