使用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

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

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, 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"))

运行效果

(结束)

相关推荐
KevinAha7 分钟前
django 实战(python 3.x/django 3/sqlite)
python·django·sqlite
凡人的AI工具箱23 分钟前
40分钟学 Go 语言高并发:RPC服务开发实战
开发语言·后端·性能优化·rpc·golang
R6bandito_29 分钟前
Qt几何数据类型:QLine类型详解(基础向)
c语言·开发语言·c++·经验分享·qt
杭电码农-NEO32 分钟前
【lua语言基础(四)】IO模型以及补充知识
开发语言·junit·lua
是十一月末39 分钟前
Python语法之正则表达式详解以及re模块中的常用函数
开发语言·python·正则表达式
一只大侠40 分钟前
计算S=1!+2!+3!+…+N!的值:JAVA
java·开发语言
一只大侠43 分钟前
输入一串字符,以“?”结束。统计其中字母个数,数字个数,其它符号个数。:JAVA
java·开发语言·算法
Oneforlove_twoforjob43 分钟前
【Java基础面试题011】什么是Java中的自动装箱和拆箱?
java·开发语言
优雅的落幕1 小时前
多线程---线程安全(synchronized)
java·开发语言·jvm
小黄编程快乐屋1 小时前
前端小练习——大雪纷飞(JS没有上限!!!)
开发语言·前端·javascript