【Pyqt6 学习笔记】实现串口调试助手,并将接收到数据模拟键盘输出

文章目录

  • 代码示例
    • main.py
    • screen_shot_module.py
    • qrcmd.py
    • untitled.py
    • untitled.ui

本文内容是 【Pyqt6 学习笔记】DIY一个二维码解析生成小工具的延申,在原来的基础上实现了串口调试助手功能,并利用 pywinautokeyboard模块将接收到数据模拟键盘输出

在这里插入图片描述
在这里插入图片描述

我这里串口连接的是SH-400模块,实现类似条码枪的功能
在这里插入图片描述

代码示例

main.py

import sysimport qrcodefrom PIL import ImageQt
from PyQt6.QtCore import pyqtSignal, QIODeviceBase
from PyQt6.QtGui import QPixmap, QImage
from PyQt6.QtSerialPort import QSerialPort, QSerialPortInfo
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt6 import QtCore
from pyzbar.pyzbar import decodefrom qrcmd import qrcmd_menu_dict
from screen_shot_module import ScreenShotWidget
from untitled import Ui_MainWindow
from pywinauto import keyboardclass ScreenShotModule(ScreenShotWidget):"""继承ScreenShotWidget类,改写 save2Clipboard、save2Local 函数,新增通过自定义信号 QImageSignal 传递截图对象的功能"""QImageSignal = pyqtSignal(QImage)  # 自定义信号def save2Clipboard(self):if self.hasScreenShot:mimData = QtCore.QMimeData()this_QImage = self.screenArea.centerPhysicalPixmap().toImage()mimData.setImageData(this_QImage)QApplication.clipboard().setMimeData(mimData)self.close()self.QImageSignal.emit(this_QImage)  # 发射图像对象def save2Local(self):fileType = self.fileType_imgfilePath, fileFormat = self.sys_selectSaveFilePath(self, fileType=fileType)if filePath:self.screenArea.centerPhysicalPixmap().save(filePath, quality=100)this_QImage = self.screenArea.centerPhysicalPixmap().toImage()self.close()self.QImageSignal.emit(this_QImage)  # 发射图像对象class MainPageWindow(QMainWindow, Ui_MainWindow):def __init__(self, parent=None):super(MainPageWindow, self).__init__(parent)self.qr_img = Noneself.setupUi(self)self.textEdit.textChanged.connect(self.display_text_edit_qr)  # 文本框切换事件与二维码生成绑定self.pushButton_save.clicked.connect(self.save_qrcode_png)self.screenShotWg = ScreenShotModule()  # 截图模块self.pushButton_screenshot.clicked.connect(self.screenShotWg.start)  # 按钮绑定截图模块self.screenShotWg.QImageSignal.connect(self.get_screenshot_QImage)  # 接收截图模块的图像# 选择扫描仪命令二维码self.comboBox_qrcmd_menu0.addItems(qrcmd_menu_dict.keys())self.comboBox_qrcmd_menu0.activated.connect(self.qrcmd_menu0_func)self.comboBox_qrcmd_menu1.activated.connect(self.qrcmd_menu1_func)self.qrcmd_menu0_func()# <editor-fold desc="串口相关功能">self.uart_decode_buffer = ""self.uart_rawdata_buffer = b""self.read_buffer = Noneself.pushButton_com_connect.clicked.connect(self.connect_uart)self.pushButton_com_disconnect.clicked.connect(self.disconnect_uart)self.serial = QSerialPort()self.refresh_serial_ports()self.pushButton_uart_refresh.clicked.connect(self.refresh_serial_ports)self.pushButton_uart_refresh.clicked.connect(self.clear_uart_textEdits)self.pushButton_uart_send.clicked.connect(self.uart_send_textEdit_uart)# </editor-fold>self.textEdit.setText('请输入要转化的文字')self.display_text_edit_qr()def clear_uart_textEdits(self):self.uart_decode_buffer = ""self.uart_rawdata_buffer = b""self.textBrowser_uart_rawdata.clear()self.textBrowser_uart_decode.clear()self.textEdit_uart.clear()# <editor-fold desc="串口相关功能">def uart_send_textEdit_uart(self):self.send_data(self.textEdit_uart.toPlainText())def refresh_serial_ports(self):self.serial_port_info_list = QSerialPortInfo.availablePorts()self.serial_list_dict = {}for com_port in self.serial_port_info_list:self.serial_list_dict['{}-{}'.format(com_port.description(), com_port.portName())] = com_portself.comboBox_com_list.clear()self.comboBox_com_list.addItems(self.serial_list_dict.keys())self.comboBox_BaudRates.clear()this_com_port_BaudRate_list = self.serial_list_dict[self.comboBox_com_list.currentText()].standardBaudRates()self.comboBox_BaudRates.addItems([str(BaudRate) for BaudRate in this_com_port_BaudRate_list])if 9600 in this_com_port_BaudRate_list:self.comboBox_BaudRates.setCurrentText('9600')self.comboBox_DataBits.clear()self.comboBox_DataBits.addItems(['Data5', 'Data6', 'Data7', 'Data8', ])self.comboBox_DataBits.setCurrentText('Data8')self.comboBox_Parity.clear()self.comboBox_Parity.addItems(['NoParity', 'EvenParity', 'OddParity', 'SpaceParity', 'MarkParity'])self.comboBox_Parity.setCurrentText('NoParity')self.comboBox_StopBits.clear()self.comboBox_StopBits.addItems(['OneStop', 'OneAndHalfStop', 'TwoStop', ])self.comboBox_StopBits.setCurrentText('OneStop')def send_data(self, data):if self.serial.isOpen():data_msg = data.encode()self.serial.write(data_msg)def on_serial_read(self):bytes_to_read = self.serial.bytesAvailable()text = self.serial.read(bytes_to_read)self.uart_rawdata_buffer += textself.textBrowser_uart_rawdata.setText(str(self.uart_rawdata_buffer)[2:-1])if self.read_buffer is None:self.read_buffer = textelse:self.read_buffer += textif b'\r' in self.read_buffer:  # 识别到结尾,进行解码this_msg = self.read_buffer.decode(encoding='GB18030', errors='replace')self.uart_decode_buffer += this_msgself.textBrowser_uart_decode.setText(self.uart_decode_buffer)if self.checkBox_keyboard_enable.isChecked():keyboard.send_keys(this_msg)if self.checkBox_keyboard_enable.isChecked():keyboard.send_keys('{ENTER}')self.read_buffer = Nonedef open_serial_port(self, port_name='COM3', baud_rate=9600, databit='Data8', parity='NoParity', stopbit='OneStop'):self.close_serial_port()self.serial.setPortName(port_name)self.serial.setBaudRate(baud_rate)self.serial.setDataBits(getattr(QSerialPort.DataBits, databit, None))self.serial.setParity(getattr(QSerialPort.Parity, parity, None))self.serial.setStopBits(getattr(QSerialPort.StopBits, stopbit, None))self.serial.setFlowControl(QSerialPort.FlowControl.NoFlowControl)if self.serial.open(QIODeviceBase.OpenModeFlag.ReadWrite):self.serial.readyRead.connect(self.on_serial_read)def close_serial_port(self):if self.serial.isOpen():self.serial.close()# </editor-fold># <editor-fold desc="选择二维码扫描仪命令">def qrcmd_menu0_func(self):self.comboBox_qrcmd_menu1.disconnect()self.comboBox_qrcmd_menu1.clear()self.comboBox_qrcmd_menu1.activated.connect(self.qrcmd_menu1_func)self.comboBox_qrcmd_menu1.addItems(qrcmd_menu_dict[self.comboBox_qrcmd_menu0.currentText()])self.qrcmd_menu1_func()def qrcmd_menu1_func(self):current_text = qrcmd_menu_dict[self.comboBox_qrcmd_menu0.currentText()][self.comboBox_qrcmd_menu1.currentText()]self.qqr_img = qrcode.make(current_text)  # 根据文本生成二维码qt_image = ImageQt.toqpixmap(self.qqr_img)  # PIL格式图片转为Qt格式图片self.pic_label.setPixmap(qt_image)  # QLabel显示图片self.textEdit.setText(current_text)# </editor-fold># <editor-fold desc="UART">def connect_uart(self):self.open_serial_port(self.serial_list_dict[self.comboBox_com_list.currentText()].portName(),int(self.comboBox_BaudRates.currentText()),self.comboBox_DataBits.currentText(),self.comboBox_Parity.currentText(),self.comboBox_StopBits.currentText(), )def disconnect_uart(self):self.close_serial_port()# </editor-fold>def save_qrcode_png(self):fileName = QFileDialog.getSaveFileName(self, "保存文件", "./", "png (*.png)")if fileName[0]:self.qr_img.save(fileName[0])def get_screenshot_QImage(self, this_QImage):"""接收截图模块的图像:param this_QImage: 来自截图模块的图像:return:"""self.label_screenshot.setPixmap(QPixmap.fromImage(this_QImage))this_Image = ImageQt.fromqimage(this_QImage)self.decode_qrcode(this_Image)def display_text_edit_qr(self):"""self.pic_label 根据 self.textEdit 的文本生成并显示对应的二维码:return:"""current_text = self.textEdit.toPlainText()self.qr_img = qrcode.make(current_text)  # 根据文本生成二维码qt_image = ImageQt.toqpixmap(self.qr_img)  # PIL格式图片转为Qt格式图片self.pic_label.setPixmap(qt_image)  # QLabel显示图片def decode_qrcode(self, qr_pil_Image):"""解析二维码:param qr_pil_Image::return:"""result = decode(qr_pil_Image)result_str = ""for i, decoded_type_obj in enumerate(result):this_qr_msg = decoded_type_obj.data.decode()result_str = "{}\n第{}个码图内容为:\n{}".format(result_str, i + 1, this_qr_msg)if result_str:self.textBrowser_show_decode_result.setText(result_str)else:self.textBrowser_show_decode_result.setText("未能成功识别截图中的码图")def run_main():app = QApplication(sys.argv)mainWindow = MainPageWindow()mainWindow.show()sys.exit(app.exec())if __name__ == '__main__':run_main()

screen_shot_module.py

# coding=utf-8"""
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010501845/article/details/124931326
"""import os
import sys
from datetime import datetime
from PyQt6 import QtCore, QtGui
from PyQt6.QtWidgets import QTextEdit, QApplication, QFontDialog, QColorDialog, QToolBar, QWidget, QFileDialog, \QMainWindow, QVBoxLayout, QPushButton
from PyQt6.QtCore import QRectF, QRect, QSizeF, QPointF, QPoint, QMarginsF
from PyQt6.QtGui import QPainter, QPen, QPixmap, QColor, QAction, QIconclass TextInputWidget(QTextEdit):"""在截图区域内的文本输入框"""def __init__(self, god=None):super().__init__(god)self.god = god# 设置背景透明# self.setStyleSheet("QTextEdit{background-color: transparent;}")palette = self.palette()palette.setBrush(QtGui.QPalette.ColorRole.Base, self.god.color_transparent)self.setPalette(palette)self.setTextColor(self.god.toolbar.curColor())self.setCurrentFont(self.god.toolbar.curFont())self._doc = self.document()  # QTextDocumentself.textChanged.connect(self.adjustSizeByContent)self.adjustSizeByContent()  # 初始化调整高度为一行self.hide()def adjustSizeByContent(self, margin=30):"""限制宽度不超出截图区域,根据文本内容调整高度,不会出现滚动条"""self._doc.setTextWidth(self.viewport().width())margins = self.contentsMargins()h = int(self._doc.size().height() + margins.top() + margins.bottom())self.setFixedHeight(h)def beginNewInput(self, pos, endPointF):"""开始新的文本输入"""self._maxRect = self.god.screenArea.normalizeRectF(pos, endPointF)self.waitForInput()def waitForInput(self):self.setGeometry(self._maxRect.toRect())# self.setGeometry(self._maxRect.adjusted(0, 0, -1, 0))  # 宽度-1self.setFocus()self.show()def loadTextInputBy(self, action):"""载入修改旧的文本action:(type, color, font, rectf, txt)"""self.setTextColor(action[1])self.setCurrentFont(action[2])self._maxRect = action[3]self.append(action[4])self.god.isDrawing = Trueself.waitForInput()class LineWidthAction(QAction):"""画笔粗细选择器"""def __init__(self, text, parent, lineWidth):super().__init__(text, parent)self._lineWidth = lineWidthself.refresh(QtCore.Qt.GlobalColor.red)self.triggered.connect(self.onTriggered)self.setVisible(False)def refresh(self, color):painter = self.parent().god.screenArea._painterdotRadius = QPointF(self._lineWidth, self._lineWidth)centerPoint = self.parent().iconPixmapCenter()pixmap = self.parent().iconPixmapCopy()painter.begin(pixmap)painter.setPen(self.parent().god.pen_transparent)painter.setBrush(color)painter.drawEllipse(QRectF(centerPoint - dotRadius, centerPoint + dotRadius))painter.end()self.setIcon(QIcon(pixmap))def onTriggered(self):self.parent()._curLineWidth = self._lineWidthclass FontAction(QAction):"""字体选择器"""def __init__(self, text, parent):super().__init__(text, parent)self.setIcon(QIcon(r"img/sys/font.png"))self._curFont = self.parent().god.font_textInputself.triggered.connect(self.onTriggered)self.setVisible(False)def onTriggered(self):font, ok = QFontDialog.getFont(self._curFont, self.parent(), caption='选择字体')if ok:self._curFont = fontself.parent().god.textInputWg.setCurrentFont(font)class ColorAction(QAction):"""颜色选择器"""def __init__(self, text, parent):super().__init__(text, parent)self._curColor = QtCore.Qt.GlobalColor.redself._pixmap = QPixmap(32, 32)self.refresh(self._curColor)self.triggered.connect(self.onTriggered)def refresh(self, color):self._curColor = colorself._pixmap.fill(color)self.setIcon(QIcon(self._pixmap))self.parent()._at_line_small.refresh(color)self.parent()._at_line_normal.refresh(color)self.parent()._at_line_big.refresh(color)def onTriggered(self):col = QColorDialog.getColor(self._curColor, self.parent(), title='选择颜色')if col.isValid():self.refresh(col)self.parent().god.textInputWg.setTextColor(col)class ScreenShotToolBar(QToolBar):"""截图区域工具条"""def __init__(self, god):super().__init__(god)self.god = godself.setToolButtonStyle(QtCore.Qt.ToolButtonStyle.ToolButtonTextUnderIcon)self.setStyleSheet("QToolBar {border-radius: 5px;padding: 3px;background-color: #eeeeef;}")self._style_normal = "QToolBar QToolButton{color: black;}"self._style_selected = "QToolBar QToolButton{color: #ff7300;border: 1px solid #BEDAF2;background-color: #D6E4F1}"  # 与鼠标悬停样式一样self._iconPixmap = QPixmap(32, 32)self._iconPixmap.fill(self.god.color_transparent)self._iconPixmapCenter = QPointF(self._iconPixmap.rect().center())self._curLineWidth = 3self._at_line_small = LineWidthAction('细', self, self._curLineWidth - 2)self._at_line_normal = LineWidthAction('中', self, self._curLineWidth)self._at_line_big = LineWidthAction('粗', self, self._curLineWidth + 2)self._at_font = FontAction('字体', self)self._at_color = ColorAction('颜色', self)self._at_rectangle = QAction(QIcon(r"img/sys/rectangle.png"), '矩形', self, triggered=self.beforeDrawRectangle)self._at_ellipse = QAction(QIcon(r"img/sys/ellipse.png"), '椭圆', self, triggered=self.beforeDrawEllipse)self._at_graffiti = QAction(QIcon(r"img/sys/graffiti.png"), '涂鸦', self, triggered=self.beforeDrawGraffiti)self._at_textInput = QAction(QIcon(r"img/sys/write.png"), '文字', self, triggered=self.beforeDrawText)self.addAction(self._at_line_small)self.addAction(self._at_line_normal)self.addAction(self._at_line_big)self.addAction(self._at_font)self.addAction(self._at_color)self.addSeparator()self.addAction(self._at_rectangle)self.addAction(self._at_ellipse)self.addAction(self._at_graffiti)self.addAction(self._at_textInput)self.addAction(QAction(QIcon(r"img/sys/undo.png"), '撤销', self, triggered=self.undo))self.addSeparator()self.addAction(QAction(QIcon(r"img/sys/logout.png"), '退出', self, triggered=self.god.close))self.addAction(QAction(QIcon(r"img/chat/download.png"), '保存', self, triggered=lambda: self.beforeSave('local')))self.addAction(QAction(QIcon(r"img/chat/sendImg.png"), '确认', self, triggered=lambda: self.beforeSave('clipboard')))self.actionTriggered.connect(self.onActionTriggered)def curLineWidth(self):return self._curLineWidthdef curFont(self):return self._at_font._curFontdef curColor(self):return self._at_color._curColor# return QColor(self._at_color._curColor.toRgb())  # 颜色的副本def iconPixmapCopy(self):return self._iconPixmap.copy()def iconPixmapCenter(self):return self._iconPixmapCenterdef onActionTriggered(self, action):"""突出显示已选中的画笔粗细、编辑模式"""for at in [self._at_line_small, self._at_line_normal, self._at_line_big]:if at._lineWidth == self._curLineWidth:self.widgetForAction(at).setStyleSheet(self._style_selected)else:self.widgetForAction(at).setStyleSheet(self._style_normal)if self.god.isDrawRectangle:self.widgetForAction(self._at_rectangle).setStyleSheet(self._style_selected)else:self.widgetForAction(self._at_rectangle).setStyleSheet(self._style_normal)if self.god.isDrawEllipse:self.widgetForAction(self._at_ellipse).setStyleSheet(self._style_selected)else:self.widgetForAction(self._at_ellipse).setStyleSheet(self._style_normal)if self.god.isDrawGraffiti:self.widgetForAction(self._at_graffiti).setStyleSheet(self._style_selected)else:self.widgetForAction(self._at_graffiti).setStyleSheet(self._style_normal)if self.god.isDrawText:self.widgetForAction(self._at_textInput).setStyleSheet(self._style_selected)else:self.widgetForAction(self._at_textInput).setStyleSheet(self._style_normal)def setLineWidthActionVisible(self, flag):self._at_line_small.setVisible(flag)self._at_line_normal.setVisible(flag)self._at_line_big.setVisible(flag)def beforeDrawRectangle(self):self.god.clearEditFlags()self.god.isDrawRectangle = Trueself.setLineWidthActionVisible(True)self._at_font.setVisible(False)def beforeDrawEllipse(self):self.god.clearEditFlags()self.god.isDrawEllipse = Trueself.setLineWidthActionVisible(True)self._at_font.setVisible(False)def beforeDrawGraffiti(self):self.god.clearEditFlags()self.god.isDrawGraffiti = Trueself.setLineWidthActionVisible(True)self._at_font.setVisible(False)def beforeDrawText(self):self.god.clearEditFlags()self.god.isDrawText = Trueself.setLineWidthActionVisible(False)self._at_font.setVisible(True)def undo(self):"""撤销上次编辑行为"""if self.god.screenArea.undoEditAction():self.god.update()def beforeSave(self, target):# 若正在编辑文本未保存,先完成编辑if self.god.isDrawing and self.god.isDrawText:self.god.screenArea.saveTextInputAction()if target == 'local':self.god.save2Local()elif target == 'clipboard':self.god.save2Clipboard()def enterEvent(self, event):self.god.setCursor(QtCore.Qt.CursorShape.ArrowCursor)  # 工具条上显示标准箭头cursordef leaveEvent(self, event):self.god.setCursor(QtCore.Qt.CursorShape.CrossCursor)  # 十字无箭头class ScreenArea(QtCore.QObject):"""屏幕区域(提供各种算法的核心类),划分为9个子区域:TopLeft,Top,TopRightLeft,Center,RightBottomLeft,Bottom,BottomRight其中Center根据start、end两个QPointF确定"""def __init__(self, god):super().__init__()self.god = godself._pt_start = QPointF()  # 划定截图区域时鼠标左键按下的位置(topLeft)self._pt_end = QPointF()  # 划定截图区域时鼠标左键松开的位置(bottomRight)self._rt_toolbar = QRectF()  # 工具条的矩形self._actions = []  # 在截图区域上的所有编辑行为(矩形、椭圆、涂鸦、文本输入等)self._pt_startEdit = QPointF()  # 在截图区域上绘制矩形、椭圆时鼠标左键按下的位置(topLeft)self._pt_endEdit = QPointF()  # 在截图区域上绘制矩形、椭圆时鼠标左键松开的位置(bottomRight)self._pointfs = []  # 涂鸦经过的所有点self._painter = QPainter()  # 独立于ScreenShotWidget之外的画家类self._textOption = QtGui.QTextOption(QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignTop)self._textOption.setWrapMode(QtGui.QTextOption.WrapMode.WrapAnywhere)  # 文本在矩形内自动换行# self._textOption.setWrapMode(QtGui.QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)self.captureScreen()def captureScreen(self):"""抓取整个屏幕的截图"""# screen = QtGui.QGuiApplication.primaryScreen()self._screenPixmap = QApplication.primaryScreen().grabWindow()self._pixelRatio = self._screenPixmap.devicePixelRatio()  # 设备像素比self._rt_screen = self.screenLogicalRectF()self.remakeNightArea()def normalizeRectF(self, topLeftPoint, bottomRightPoint):"""根据起止点生成宽高非负数的QRectF,通常用于bottomRightPoint比topLeftPoint更左更上的情况入参可以是QPoint或QPointF"""rectf = QRectF(topLeftPoint, bottomRightPoint)x = rectf.x()y = rectf.y()w = rectf.width()h = rectf.height()if w < 0:  # bottomRightPoint在topLeftPoint左侧时,topLeftPoint往左移动x = x + ww = -wif h < 0:  # bottomRightPoint在topLeftPoint上侧时,topLeftPoint往上移动y = y + hh = -hreturn QRectF(x, y, w, h)def physicalRectF(self, rectf):"""计算划定的截图区域的(缩放倍率1.0的)原始矩形(会变大)rectf:划定的截图区域的矩形。可为QRect或QRectF"""return QRectF(rectf.x() * self._pixelRatio, rectf.y() * self._pixelRatio,rectf.width() * self._pixelRatio, rectf.height() * self._pixelRatio)def logicalRectF(self, physicalRectF):"""根据原始矩形计算缩放后的矩形(会变小)physicalRectF:缩放倍率1.0的原始矩形。可为QRect或QRectF"""return QRectF(physicalRectF.x() / self._pixelRatio, physicalRectF.y() / self._pixelRatio,physicalRectF.width() / self._pixelRatio, physicalRectF.height() / self._pixelRatio)def physicalPixmap(self, rectf, editAction=False):"""根据指定区域获取其原始大小的(缩放倍率1.0的)QPixmaprectf:指定区域。可为QRect或QRectFeditAction:是否带上编辑结果"""if editAction:canvasPixmap = self.screenPhysicalPixmapCopy()self._painter.begin(canvasPixmap)self.paintEachEditAction(self._painter, textBorder=False)self._painter.end()return canvasPixmap.copy(self.physicalRectF(rectf).toRect())else:return self._screenPixmap.copy(self.physicalRectF(rectf).toRect())def screenPhysicalRectF(self):return QRectF(self._screenPixmap.rect())def screenLogicalRectF(self):return QRectF(QPointF(0, 0), self.screenLogicalSizeF())  # 即当前屏幕显示的大小def screenPhysicalSizeF(self):return QSizeF(self._screenPixmap.size())def screenLogicalSizeF(self):return QSizeF(self._screenPixmap.width() / self._pixelRatio, self._screenPixmap.height() / self._pixelRatio)def screenPhysicalPixmapCopy(self):return self._screenPixmap.copy()def screenLogicalPixmapCopy(self):return self._screenPixmap.scaled(self.screenLogicalSizeF().toSize())def centerPhysicalRectF(self):return self.physicalRectF(self._rt_center)def centerLogicalRectF(self):"""根据屏幕上的start、end两个QPointF确定"""return self._rt_centerdef centerPhysicalPixmap(self, editAction=True):"""截图区域的QPixmapeditAction:是否带上编辑结果"""return self.physicalPixmap(self._rt_center + QMarginsF(-1, -1, 1, 1), editAction=editAction)def centerTopMid(self):return self._pt_centerTopMiddef centerBottomMid(self):return self._pt_centerBottomMiddef centerLeftMid(self):return self._pt_centerLeftMiddef centerRightMid(self):return self._pt_centerRightMiddef setStartPoint(self, pointf, remake=False):self._pt_start = pointfif remake:self.remakeNightArea()def setEndPoint(self, pointf, remake=False):self._pt_end = pointfif remake:self.remakeNightArea()def setCenterArea(self, start, end):self._pt_start = startself._pt_end = endself.remakeNightArea()def remakeNightArea(self):"""重新划分九宫格区域。根据中央截图区域计算出来的其他8个区域、截图区域四个边框中点坐标等都是logical的"""self._rt_center = self.normalizeRectF(self._pt_start, self._pt_end)# 中央区域上下左右边框的中点,用于调整大小self._pt_centerTopMid = (self._rt_center.topLeft() + self._rt_center.topRight()) / 2self._pt_centerBottomMid = (self._rt_center.bottomLeft() + self._rt_center.bottomRight()) / 2self._pt_centerLeftMid = (self._rt_center.topLeft() + self._rt_center.bottomLeft()) / 2self._pt_centerRightMid = (self._rt_center.topRight() + self._rt_center.bottomRight()) / 2# 以截图区域左上、上中、右上、左中、右中、左下、下中、右下为中心的正方形区域,用于调整大小self._square_topLeft = self.squareAreaByCenter(self._rt_center.topLeft())self._square_topRight = self.squareAreaByCenter(self._rt_center.topRight())self._square_bottomLeft = self.squareAreaByCenter(self._rt_center.bottomLeft())self._square_bottomRight = self.squareAreaByCenter(self._rt_center.bottomRight())self._square_topMid = self.squareAreaByCenter(self._pt_centerTopMid)self._square_bottomMid = self.squareAreaByCenter(self._pt_centerBottomMid)self._square_leftMid = self.squareAreaByCenter(self._pt_centerLeftMid)self._square_rightMid = self.squareAreaByCenter(self._pt_centerRightMid)# 除中央截图区域外的8个区域self._rt_topLeft = QRectF(self._rt_screen.topLeft(), self._rt_center.topLeft())self._rt_top = QRectF(QPointF(self._rt_center.topLeft().x(), 0), self._rt_center.topRight())self._rt_topRight = QRectF(QPointF(self._rt_center.topRight().x(), 0),QPointF(self._rt_screen.width(), self._rt_center.topRight().y()))self._rt_left = QRectF(QPointF(0, self._rt_center.topLeft().y()), self._rt_center.bottomLeft())self._rt_right = QRectF(self._rt_center.topRight(),QPointF(self._rt_screen.width(), self._rt_center.bottomRight().y()))self._rt_bottomLeft = QRectF(QPointF(0, self._rt_center.bottomLeft().y()),QPointF(self._rt_center.bottomLeft().x(), self._rt_screen.height()))self._rt_bottom = QRectF(self._rt_center.bottomLeft(),QPointF(self._rt_center.bottomRight().x(), self._rt_screen.height()))self._rt_bottomRight = QRectF(self._rt_center.bottomRight(), self._rt_screen.bottomRight())def squareAreaByCenter(self, pointf):"""以QPointF为中心的正方形QRectF"""rectf = QRectF(0, 0, 15, 15)rectf.moveCenter(pointf)return rectfdef aroundAreaIn8Direction(self):"""中央区域周边的8个方向的区域(无交集)"""return [self._rt_topLeft, self._rt_top, self._rt_topRight,self._rt_left, self._rt_right,self._rt_bottomLeft, self._rt_bottom, self._rt_bottomRight]def aroundAreaIn4Direction(self):"""中央区域周边的4个方向的区域(有交集)上区域(左上、上、右上):0, 0, maxX, topRight.y下区域(左下、下、右下):0, bottomLeft.y, maxX, maxY-bottomLeft.y左区域(左上、左、左下):0, 0, bottomLeft.x, maxY右区域(右上、右、右下):topRight.x, 0, maxX - topRight.x, maxY"""screenSizeF = self.screenLogicalSizeF()pt_topRight = self._rt_center.topRight()pt_bottomLeft = self._rt_center.bottomLeft()return [QRectF(0, 0, screenSizeF.width(), pt_topRight.y()),QRectF(0, pt_bottomLeft.y(), screenSizeF.width(), screenSizeF.height() - pt_bottomLeft.y()),QRectF(0, 0, pt_bottomLeft.x(), screenSizeF.height()),QRectF(pt_topRight.x(), 0, screenSizeF.width() - pt_topRight.x(), screenSizeF.height())]def aroundAreaWithoutIntersection(self):"""中央区域周边的4个方向的区域(无交集)上区域(左上、上、右上):0, 0, maxX, topRight.y下区域(左下、下、右下):0, bottomLeft.y, maxX, maxY-bottomLeft.y左区域(左):0, topRight.y, bottomLeft.x-1, center.height右区域(右):topRight.x+1, topRight.y, maxX - topRight.x, center.height"""screenSizeF = self.screenLogicalSizeF()pt_topRight = self._rt_center.topRight()pt_bottomLeft = self._rt_center.bottomLeft()centerHeight = pt_bottomLeft.y() - pt_topRight.y()return [QRectF(0, 0, screenSizeF.width(), pt_topRight.y()),QRectF(0, pt_bottomLeft.y(), screenSizeF.width(), screenSizeF.height() - pt_bottomLeft.y()),QRectF(0, pt_topRight.y(), pt_bottomLeft.x() - 1, centerHeight),QRectF(pt_topRight.x() + 1, pt_topRight.y(), screenSizeF.width() - pt_topRight.x(), centerHeight)]def setBeginDragPoint(self, pointf):"""计算开始拖拽位置距离截图区域左上角的向量"""self._drag_vector = pointf - self._rt_center.topLeft()def getNewPosAfterDrag(self, pointf):"""计算拖拽后截图区域左上角的新位置"""return pointf - self._drag_vectordef moveCenterAreaTo(self, pointf):"""限制拖拽不能超出屏幕范围"""self._rt_center.moveTo(self.getNewPosAfterDrag(pointf))startPointF = self._rt_center.topLeft()if startPointF.x() < 0:self._rt_center.moveTo(0, startPointF.y())startPointF = self._rt_center.topLeft()if startPointF.y() < 0:self._rt_center.moveTo(startPointF.x(), 0)screenSizeF = self.screenLogicalSizeF()endPointF = self._rt_center.bottomRight()if endPointF.x() > screenSizeF.width():self._rt_center.moveBottomRight(QPointF(screenSizeF.width(), endPointF.y()))endPointF = self._rt_center.bottomRight()if endPointF.y() > screenSizeF.height():self._rt_center.moveBottomRight(QPointF(endPointF.x(), screenSizeF.height()))self.setCenterArea(self._rt_center.topLeft(), self._rt_center.bottomRight())def setBeginAdjustPoint(self, pointf):"""判断开始调整截图区域大小时鼠标左键在哪个区(不可能是中央区域),用于判断调整大小的意图方向"""self._mousePos = self.getMousePosBy(pointf)def getMousePosBy(self, pointf):if self._square_topLeft.contains(pointf):return 'TL'elif self._square_topMid.contains(pointf):return 'T'elif self._square_topRight.contains(pointf):return 'TR'elif self._square_leftMid.contains(pointf):return 'L'elif self._rt_center.contains(pointf):return 'CENTER'elif self._square_rightMid.contains(pointf):return 'R'elif self._square_bottomLeft.contains(pointf):return 'BL'elif self._square_bottomMid.contains(pointf):return 'B'elif self._square_bottomRight.contains(pointf):return 'BR'else:return 'ERROR'def adjustCenterAreaBy(self, pointf):"""根据开始调整截图区域大小时鼠标左键在哪个区(不可能是中央区域),判断调整大小的意图方向,判定新的开始、结束位置"""startPointF = self._rt_center.topLeft()endPointF = self._rt_center.bottomRight()if self._mousePos == 'TL':startPointF = pointfelif self._mousePos == 'T':startPointF = QPointF(startPointF.x(), pointf.y())elif self._mousePos == 'TR':startPointF = QPointF(startPointF.x(), pointf.y())endPointF = QPointF(pointf.x(), endPointF.y())elif self._mousePos == 'L':startPointF = QPointF(pointf.x(), startPointF.y())elif self._mousePos == 'R':endPointF = QPointF(pointf.x(), endPointF.y())elif self._mousePos == 'BL':startPointF = QPointF(pointf.x(), startPointF.y())endPointF = QPointF(endPointF.x(), pointf.y())elif self._mousePos == 'B':endPointF = QPointF(endPointF.x(), pointf.y())elif self._mousePos == 'BR':endPointF = pointfelse:  # 'ERROR'returnnewRectF = self.normalizeRectF(startPointF, endPointF)self.setCenterArea(newRectF.topLeft(), newRectF.bottomRight())def getMouseShapeBy(self, pointf):"""根据鼠标位置返回对应的鼠标样式"""if self._rt_center.contains(pointf):if self.god.isDrawRectangle or self.god.isDrawEllipse:return QtCore.Qt.CursorShape.ArrowCursorelif self.god.isDrawGraffiti:return QtCore.Qt.CursorShape.PointingHandCursor  # 超链接上的手势elif self.god.isDrawText:return QtCore.Qt.CursorShape.IBeamCursor  # 工字else:return QtCore.Qt.CursorShape.SizeAllCursor  # 十字有箭头# return QtCore.Qt.CursorShape.OpenHandCursor  # 打开的手,表示可拖拽elif self._square_topLeft.contains(pointf) or self._square_bottomRight.contains(pointf):return QtCore.Qt.CursorShape.SizeFDiagCursor  # ↖↘elif self._square_topMid.contains(pointf) or self._square_bottomMid.contains(pointf):return QtCore.Qt.CursorShape.SizeVerCursor  # ↑↓elif self._square_topRight.contains(pointf) or self._square_bottomLeft.contains(pointf):return QtCore.Qt.CursorShape.SizeBDiagCursor  # ↙↗elif self._square_leftMid.contains(pointf) or self._square_rightMid.contains(pointf):return QtCore.Qt.CursorShape.SizeHorCursor  # ←→else:return QtCore.Qt.CursorShape.CrossCursor  # 十字无箭头def isMousePosInCenterRectF(self, pointf):return self._rt_center.contains(pointf)def paintMagnifyingGlassPixmap(self, pos, glassSize):"""绘制放大镜内的图像(含纵横十字线)pos:鼠标光标位置glassSize:放大镜边框大小"""pixmapRect = QRect(0, 0, 20, 20)  # 以鼠标光标为中心的正方形区域,最好是偶数pixmapRect.moveCenter(pos)glassPixmap = self.physicalPixmap(pixmapRect)glassPixmap.setDevicePixelRatio(1.0)glassPixmap = glassPixmap.scaled(glassSize, glassSize, QtCore.Qt.AspectRatioMode.KeepAspectRatio)# 在放大后的QPixmap上画纵横十字线self._painter.begin(glassPixmap)halfWidth = glassPixmap.width() / 2halfHeight = glassPixmap.height() / 2self._painter.setPen(self.god.pen_SolidLine_lightBlue)self._painter.drawLine(QPointF(0, halfHeight), QPointF(glassPixmap.width(), halfHeight))self._painter.drawLine(QPointF(halfWidth, 0), QPointF(halfWidth, glassPixmap.height()))self._painter.end()return glassPixmapdef paintEachEditAction(self, painter, textBorder=True):"""绘制所有已保存的编辑行为。编辑行为超出截图区域也无所谓,保存图像时只截取截图区域内textBorder:是否绘制文本边框"""for action in self.getEditActions():if action[0] == 'rectangle':  # (type, color, lineWidth, startPoint, endPoint)self.paintRectangle(painter, action[1], action[2], action[3], action[4])elif action[0] == 'ellipse':  # (type, color, lineWidth, startPoint, endPoint)self.paintEllipse(painter, action[1], action[2], action[3], action[4])elif action[0] == 'graffiti':  # (type, color, lineWidth, points)self.paintGraffiti(painter, action[1], action[2], action[3])elif action[0] == 'text':  # (type, color, font, rectf, txt)self.paintTextInput(painter, action[1], action[2], action[3], action[4], textBorder=textBorder)def paintRectangle(self, painter, color, lineWidth, startPoint=None, endPoint=None):if not startPoint:startPoint = self._pt_startEditif not endPoint:endPoint = self._pt_endEditqrectf = self.normalizeRectF(startPoint, endPoint)if qrectf.isValid():pen = QPen(color)pen.setWidth(lineWidth)painter.setPen(pen)painter.setBrush(self.god.color_transparent)painter.drawRect(qrectf)def paintEllipse(self, painter, color, lineWidth, startPoint=None, endPoint=None):if not startPoint:startPoint = self._pt_startEditif not endPoint:endPoint = self._pt_endEditqrectf = self.normalizeRectF(startPoint, endPoint)if qrectf.isValid():pen = QPen(color)pen.setWidth(lineWidth)painter.setPen(pen)painter.setBrush(self.god.color_transparent)painter.drawEllipse(qrectf)def paintGraffiti(self, painter, color, lineWidth, pointfs=None):if not pointfs:pointfs = self.getGraffitiPointFs()pen = QPen(color)pen.setWidth(lineWidth)painter.setPen(pen)total = len(pointfs)if total == 0:returnelif total == 1:painter.drawPoint(pointfs[0])else:previousPoint = pointfs[0]for i in range(1, total):nextPoint = pointfs[i]painter.drawLine(previousPoint, nextPoint)previousPoint = nextPointdef paintTextInput(self, painter, color, font, rectf, txt, textBorder=True):painter.setPen(color)painter.setFont(font)painter.drawText(rectf, txt, self._textOption)if textBorder:painter.setPen(QtCore.Qt.PenStyle.DotLine)  # 点线painter.setBrush(self.god.color_transparent)painter.drawRect(rectf)def getEditActions(self):return self._actions.copy()def takeTextInputActionAt(self, pointf):"""根据鼠标位置查找已保存的文本输入结果,找到后取出"""for i in range(len(self._actions)):action = self._actions[i]if action[0] == 'text' and action[3].contains(pointf):return self._actions.pop(i)return Nonedef undoEditAction(self):reply = Falseif self._actions:reply = self._actions.pop()if not self._actions:  # 所有编辑行为都被撤销后退出编辑模式self.god.exitEditMode()else:self.god.exitEditMode()return replydef clearEditActions(self):self._actions.clear()def setBeginEditPoint(self, pointf):"""在截图区域上绘制矩形、椭圆时鼠标左键按下的位置(topLeft)"""self._pt_startEdit = pointfself.god.isDrawing = Truedef setEndEditPoint(self, pointf):"""在截图区域上绘制矩形、椭圆时鼠标左键松开的位置(bottomRight)"""self._pt_endEdit = pointfdef saveRectangleAction(self):rectf = self.normalizeRectF(self._pt_startEdit, self._pt_endEdit)self._actions.append(('rectangle', self.god.toolbar.curColor(), self.god.toolbar.curLineWidth(),rectf.topLeft(), rectf.bottomRight()))self._pt_startEdit = QPointF()self._pt_endEdit = QPointF()self.god.isDrawing = Falsedef saveEllipseleAction(self):rectf = self.normalizeRectF(self._pt_startEdit, self._pt_endEdit)self._actions.append(('ellipse', self.god.toolbar.curColor(), self.god.toolbar.curLineWidth(),rectf.topLeft(), rectf.bottomRight()))self._pt_startEdit = QPointF()self._pt_endEdit = QPointF()self.god.isDrawing = Falsedef saveGraffitiPointF(self, pointf, first=False):self._pointfs.append(pointf)if first:self.god.isDrawing = Truedef getGraffitiPointFs(self):return self._pointfs.copy()def saveGraffitiAction(self):if self._pointfs:self._actions.append(('graffiti', self.god.toolbar.curColor(), self.god.toolbar.curLineWidth(), self._pointfs.copy()))self._pointfs.clear()self.god.isDrawing = Falsedef setBeginInputTextPoint(self, pointf):"""在截图区域上输入文字时鼠标左键按下的位置(topLeft)"""self.god.isDrawing = Trueself.god.textInputWg.beginNewInput(pointf, self._pt_end)def saveTextInputAction(self):txt = self.god.textInputWg.toPlainText()if txt:rectf = self.god.textInputWg._maxRect  # 取最大矩形的topLeftrectf.setSize(QRectF(self.god.textInputWg.rect()).size())  # 取实际矩形的宽高self._actions.append(('text', self.god.toolbar.curColor(), self.god.toolbar.curFont(),rectf, txt))self.god.textInputWg.clear()self.god.textInputWg.hide()  # 不管保存成功与否都取消编辑self.god.isDrawing = Falsedef saveNightAreaImg(self):"""将九宫格区域保存为本地图片,仅用于开发测试"""screenPixmap = self.screenPhysicalPixmapCopy()self._painter.begin(screenPixmap)self._painter.setPen(self.pen_SolidLine_lightBlue)self._painter.setFont(self.god.font_normal)self._painter.drawRect(self._rt_center)for area in self.aroundAreaIn8Direction():self._painter.drawRect(area)for pointf in [self._rt_center.topLeft(), self._rt_center.topRight(),self._rt_center.bottomLeft(), self._rt_center.bottomRight(),self._pt_centerTopMid, self._pt_centerBottomMid,self._pt_centerLeftMid, self._pt_centerRightMid]:self._painter.drawText(pointf + QPointF(5, -5), '(%s, %s)' % (pointf.x(), pointf.y()))self._painter.end()screenPixmap.save('1.jpg', quality=100)self.centerPhysicalPixmap().save('2.jpg', quality=100)class ScreenShotWidget(QWidget):fileType_all = '所有文件 (*);;Excel文件 (*.xls *.xlsx);;图片文件 (*.jpg *.jpeg *.gif *.png *.bmp)'fileType_img = '图片文件 (*.jpg *.jpeg *.gif *.png *.bmp)'dir_lastAccess = os.getcwd()  # 最后访问目录def __init__(self):super().__init__()self.setMouseTracking(True)self.setWindowFlags(QtCore.Qt.WindowType.FramelessWindowHint | QtCore.Qt.WindowType.WindowStaysOnTopHint)self.initPainterTool()self.initFunctionalFlag()self.screenArea = ScreenArea(self)self.toolbar = ScreenShotToolBar(self)self.textInputWg = TextInputWidget(self)# 设置 screenPixmap 为窗口背景# palette = QtGui.QPalette()# palette.setBrush(QtGui.QPalette.ColorRole.Window, QtGui.QBrush(self.screenArea.screenPhysicalPixmapCopy()))# self.setPalette(palette)def start(self):self.screenArea.captureScreen()self.setGeometry(self.screenArea.screenPhysicalRectF().toRect())self.clearScreenShotArea()self.showFullScreen()def initPainterTool(self):self.painter = QPainter()self.color_transparent = QtCore.Qt.GlobalColor.transparentself.color_black = QColor(0, 0, 0, 64)  # 黑色背景self.color_lightBlue = QColor(30, 120, 255)  # 浅蓝色。深蓝色QtCore.Qt.GlobalColor.blueself.font_normal = QtGui.QFont('Times New Roman', 11, QtGui.QFont.Weight.Normal)self.font_textInput = QtGui.QFont('微软雅黑', 16, QtGui.QFont.Weight.Normal)  # 工具条文字工具默认字体self.pen_transparent = QPen(QtCore.Qt.PenStyle.NoPen)  # 没有笔迹,画不出线条self.pen_white = QPen(QtCore.Qt.GlobalColor.white)self.pen_SolidLine_lightBlue = QPen(self.color_lightBlue)  # 实线,浅蓝色self.pen_SolidLine_lightBlue.setStyle(QtCore.Qt.PenStyle.DashLine)  # 实线SolidLine,虚线DashLine,点线DotLineself.pen_SolidLine_lightBlue.setWidthF(0)  # 0表示线宽为1self.pen_DashLine_lightBlue = QPen(self.color_lightBlue)  # 虚线,浅蓝色self.pen_DashLine_lightBlue.setStyle(QtCore.Qt.PenStyle.DashLine)def initFunctionalFlag(self):self.hasScreenShot = False  # 是否已通过拖动鼠标左键划定截图区域self.isCapturing = False  # 正在拖动鼠标左键选定截图区域时self.isMoving = False  # 在截图区域内拖动时self.isAdjusting = False  # 在截图区域的边框按住鼠标左键调整大小时self.isDrawing = False  # 是否已在截图区域内开始绘制self.isDrawRectangle = False  # 正在截图区域内画矩形self.isDrawEllipse = False  # 正在截图区域内画椭圆self.isDrawGraffiti = False  # 正在截图区域内进行涂鸦self.isDrawText = False  # 正在截图区域内画文字self.setCursor(QtCore.Qt.CursorShape.CrossCursor)  # 设置鼠标样式 十字def paintEvent(self, event):centerRectF = self.screenArea.centerLogicalRectF()screenSizeF = self.screenArea.screenLogicalSizeF()canvasPixmap = self.screenArea.screenPhysicalPixmapCopy()# canvasPixmap = QPixmap(screenSizeF.toSize())# canvasPixmap.fill(self.color_transparent)# 在屏幕截图的副本上绘制已选定的截图区域self.painter.begin(canvasPixmap)if self.hasScreenShot:self.paintCenterArea(centerRectF)  # 绘制中央截图区域self.paintMaskLayer(screenSizeF, fullScreen=False)  # 绘制截图区域的周边区域遮罩层else:self.paintMaskLayer(screenSizeF)self.paintMagnifyingGlass(screenSizeF)  # 在鼠标光标右下角显示放大镜self.paintToolbar(centerRectF, screenSizeF)  # 在截图区域右下角显示工具条self.paintEditActions()  # 在截图区域绘制编辑行为结果self.painter.end()# 把画好的绘制结果显示到窗口上self.painter.begin(self)self.painter.drawPixmap(0, 0, canvasPixmap)  # 从坐标(0, 0)开始绘制self.painter.end()def paintCenterArea(self, centerRectF):"""绘制已选定的截图区域"""self.painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)  # 反走样# 1.绘制矩形线框self.painter.setPen(self.pen_DashLine_lightBlue)self.painter.drawRect(centerRectF)# 2.绘制矩形线框4个端点和4条边框的中间点if centerRectF.width() >= 100 and centerRectF.height() >= 100:points = [  # 点坐标centerRectF.topLeft(), centerRectF.topRight(), centerRectF.bottomLeft(), centerRectF.bottomRight(),self.screenArea.centerLeftMid(), self.screenArea.centerRightMid(),self.screenArea.centerTopMid(), self.screenArea.centerBottomMid()]blueDotRadius = QPointF(2, 2)  # 椭圆蓝点self.painter.setBrush(self.color_lightBlue)for point in points:self.painter.drawEllipse(QRectF(point - blueDotRadius, point + blueDotRadius))# 3.在截图区域左上角显示截图区域宽高if centerRectF.topLeft().y() > 20:labelPos = centerRectF.topLeft() + QPointF(5, -5)else:  # 拖拽截图区域到贴近屏幕上边缘时“宽x高”移动到截图区域左上角的下侧labelPos = centerRectF.topLeft() + QPointF(5, 15)centerPhysicalRect = self.screenArea.centerPhysicalRectF().toRect()self.painter.setPen(self.pen_white)self.painter.setFont(self.font_normal)self.painter.drawText(labelPos, '%s x %s' % (centerPhysicalRect.width(), centerPhysicalRect.height()))# 4.在屏幕左上角预览截图结果# self.painter.drawPixmap(0, 0, self.screenArea.centerPhysicalPixmap())  # 从坐标(0, 0)开始绘制def paintMaskLayer(self, screenSizeF, fullScreen=True):if fullScreen:  # 全屏遮罩层maskPixmap = QPixmap(screenSizeF.toSize())maskPixmap.fill(self.color_black)self.painter.drawPixmap(0, 0, maskPixmap)else:  # 绘制截图区域的周边区域遮罩层,以凸显截图区域# 方法一:截图区域以外的8个方向区域# for area in self.screenArea.aroundAreaIn8Direction():#     area = area.normalized()#     maskPixmap = QPixmap(area.size().toSize())  # 由于float转int的精度问题,可能会存在黑线条缝隙#     maskPixmap.fill(self.color_black)#     self.painter.drawPixmap(area.topLeft(), maskPixmap)# 方法二:截图区域以外的上下左右区域(有交集,交集部分颜色加深,有明显的纵横效果)# for area in self.screenArea.aroundAreaIn4Direction():#     maskPixmap = QPixmap(area.size().toSize())#     maskPixmap.fill(self.color_black)#     self.painter.drawPixmap(area.topLeft(), maskPixmap)# 方法三:截图区域以外的上下左右区域(无交集)for area in self.screenArea.aroundAreaWithoutIntersection():maskPixmap = QPixmap(area.size().toSize())maskPixmap.fill(self.color_black)self.painter.drawPixmap(area.topLeft(), maskPixmap)def paintMagnifyingGlass(self, screenSizeF, glassSize=150, offset=30, labelHeight=30):"""未划定截图区域模式时、正在划定截取区域时、调整截取区域大小时在鼠标光标右下角显示放大镜glassSize:放大镜正方形边长offset:放大镜任意一个端点距离鼠标光标位置的最近距离labelHeight:pos和rgb两行文字的高度"""if self.hasScreenShot and (not self.isCapturing) and (not self.isAdjusting):returnpos = QtGui.QCursor.pos()glassPixmap = self.screenArea.paintMagnifyingGlassPixmap(pos, glassSize)  # 画好纵横十字线后的放大镜内QPixmap# 限制放大镜显示不超出屏幕外glassRect = glassPixmap.rect()if (pos.x() + glassSize + offset) < screenSizeF.width():if (pos.y() + offset + glassSize + labelHeight) < screenSizeF.height():glassRect.moveTo(pos + QPoint(offset, offset))else:glassRect.moveBottomLeft(pos + QPoint(offset, -offset))else:if (pos.y() + offset + glassSize + labelHeight) < screenSizeF.height():glassRect.moveTopRight(pos + QPoint(-offset, offset))else:glassRect.moveBottomRight(pos + QPoint(-offset, -offset))self.painter.drawPixmap(glassRect.topLeft(), glassPixmap)# 显示pos:(x, y)、rgb:(255,255,255)qrgb = QtGui.QRgba64.fromArgb32(glassPixmap.toImage().pixel(glassPixmap.rect().center()))labelRectF = QRectF(glassRect.bottomLeft().x(), glassRect.bottomLeft().y(), glassSize, labelHeight)self.painter.setPen(self.pen_transparent)self.painter.setBrush(self.color_black)  # 黑底self.painter.drawRect(labelRectF)self.painter.setPen(self.pen_white)self.painter.setFont(self.font_normal)self.painter.drawText(labelRectF,QtCore.Qt.AlignmentFlag.AlignLeft | QtCore.Qt.AlignmentFlag.AlignVCenter,'pos:(%s, %s)\nrgb:(%s, %s, %s)' % (pos.x(), pos.y(), qrgb.red8(), qrgb.green8(), qrgb.blue8()))def paintToolbar(self, centerRectF, screenSizeF):"""在截图区域右下角显示工具条"""if self.hasScreenShot:if self.isCapturing or self.isAdjusting:self.toolbar.hide()  # 正在划定截取区域时、调整截图区域大小时不显示工具条else:self.toolbar.adjustSize()toolbarRectF = QRectF(self.toolbar.rect())# 工具条位置优先顺序:右下角下侧,右上角上侧,右下角上侧if (screenSizeF.height() - centerRectF.bottomRight().y()) > toolbarRectF.height():toolbarRectF.moveTopRight(centerRectF.bottomRight() + QPointF(-5, 5))elif centerRectF.topRight().y() > toolbarRectF.height():toolbarRectF.moveBottomRight(centerRectF.topRight() + QPointF(-5, -5))else:toolbarRectF.moveBottomRight(centerRectF.bottomRight() + QPointF(-5, -5))# 限制工具条的x坐标不为负数,不能移出屏幕外if toolbarRectF.x() < 0:pos = toolbarRectF.topLeft()pos.setX(centerRectF.x() + 5)toolbarRectF.moveTo(pos)self.toolbar.move(toolbarRectF.topLeft().toPoint())self.toolbar.show()else:self.toolbar.hide()def paintEditActions(self):"""在截图区域绘制编辑行为结果。编辑行为超出截图区域也无所谓,保存图像时只截取截图区域内"""# 1.绘制正在拖拽编辑中的矩形、椭圆、涂鸦if self.isDrawRectangle:self.screenArea.paintRectangle(self.painter, self.toolbar.curColor(), self.toolbar.curLineWidth())elif self.isDrawEllipse:self.screenArea.paintEllipse(self.painter, self.toolbar.curColor(), self.toolbar.curLineWidth())elif self.isDrawGraffiti:self.screenArea.paintGraffiti(self.painter, self.toolbar.curColor(), self.toolbar.curLineWidth())# 2.绘制所有已保存的编辑行为self.screenArea.paintEachEditAction(self.painter)def clearEditFlags(self):self.isDrawing = Falseself.isDrawRectangle = Falseself.isDrawEllipse = Falseself.isDrawGraffiti = Falseself.isDrawText = Falsedef exitEditMode(self):"""退出编辑模式"""self.clearEditFlags()self.toolbar.onActionTriggered(None)  # 清空工具条工具按钮选中状态self.textInputWg.hide()def clearScreenShotArea(self):"""清空已划定的截取区域"""self.screenArea.clearEditActions()  # 清除已保存的编辑行为self.exitEditMode()self.hasScreenShot = Falseself.isCapturing = Falsepos = QPointF()self.screenArea.setCenterArea(pos, pos)self.update()self.setCursor(QtCore.Qt.CursorShape.CrossCursor)  # 设置鼠标样式 十字def mousePressEvent(self, event):if event.button() == QtCore.Qt.MouseButton.LeftButton:pos = event.position()if self.hasScreenShot:if self.isDrawRectangle or self.isDrawEllipse:self.screenArea.setBeginEditPoint(pos)elif self.isDrawGraffiti:  # 保存涂鸦经过的每一个点self.screenArea.saveGraffitiPointF(pos, first=True)elif self.isDrawText:if self.isDrawing:if QRectF(self.textInputWg.rect()).contains(pos):pass  # 在输入框内调整光标位置,忽略else:  # 鼠标点到输入框之外,完成编辑self.screenArea.saveTextInputAction()else:  # 未开始编辑时(暂不支持文本拖拽)action = self.screenArea.takeTextInputActionAt(pos)if action:  # 鼠标点到输入框之内,修改旧的文本输入self.textInputWg.loadTextInputBy(action)else:  # 鼠标点到输入框之外,开始新的文本输入self.screenArea.setBeginInputTextPoint(pos)elif self.screenArea.isMousePosInCenterRectF(pos):self.isMoving = True  # 进入拖拽移动模式self.screenArea.setBeginDragPoint(pos)else:self.isAdjusting = True  # 进入调整大小模式self.screenArea.setBeginAdjustPoint(pos)else:self.screenArea.setCenterArea(pos, pos)self.isCapturing = True  # 进入划定截图区域模式if event.button() == QtCore.Qt.MouseButton.RightButton:if self.hasScreenShot or self.isCapturing:  # 清空已划定的的截图区域self.clearScreenShotArea()else:self.close()def mouseReleaseEvent(self, event):if event.button() == QtCore.Qt.MouseButton.LeftButton:if self.isDrawRectangle:self.screenArea.saveRectangleAction()elif self.isDrawEllipse:self.screenArea.saveEllipseleAction()elif self.isDrawGraffiti:self.screenArea.saveGraffitiAction()self.isCapturing = Falseself.isMoving = Falseself.isAdjusting = Falseself.toolbar.show()def mouseMoveEvent(self, event):pos = event.position()if self.isDrawing:if self.isDrawRectangle or self.isDrawEllipse:self.screenArea.setEndEditPoint(pos)elif self.isDrawGraffiti:self.screenArea.saveGraffitiPointF(pos)elif self.isCapturing:self.hasScreenShot = Trueself.screenArea.setEndPoint(pos, remake=True)elif self.isMoving:self.screenArea.moveCenterAreaTo(pos)elif self.isAdjusting:self.screenArea.adjustCenterAreaBy(pos)self.update()if self.hasScreenShot:self.setCursor(self.screenArea.getMouseShapeBy(pos))else:self.setCursor(QtCore.Qt.CursorShape.CrossCursor)  # 设置鼠标样式 十字def mouseDoubleClickEvent(self, event):if event.button() == QtCore.Qt.MouseButton.LeftButton:if self.screenArea.isMousePosInCenterRectF(event.position()):self.save2Clipboard()self.close()def keyPressEvent(self, QKeyEvent):if QKeyEvent.key() == QtCore.Qt.Key.Key_Escape:self.close()if QKeyEvent.key() in (QtCore.Qt.Key.Key_Return, QtCore.Qt.Key.Key_Enter):  # 大键盘、小键盘回车self.save2Clipboard()self.close()def save2Clipboard(self):"""将截图区域复制到剪贴板"""if self.hasScreenShot:mimData = QtCore.QMimeData()mimData.setImageData(self.screenArea.centerPhysicalPixmap().toImage())QApplication.clipboard().setMimeData(mimData)# self.screenArea.saveNightAreaImg()self.close()def save2Local(self):fileType = self.fileType_imgfilePath, fileFormat = self.sys_selectSaveFilePath(self, fileType=fileType)if filePath:self.screenArea.centerPhysicalPixmap().save(filePath, quality=100)self.close()def sys_getCurTime(self, fmt='%Y-%m-%d %H:%M:%S'):"""获取字符串格式的当前时间"""# return QtCore.QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss')return datetime.now().strftime(fmt)def sys_selectSaveFilePath(self, widget, title='选择文件保存路径', saveFileDir=None,saveFileName='', defaultFileFmt='%Y%m%d%H%M%S', fileType=None):"""选择文件保存路径title:选择窗口标题saveFileDir:指定保存目录saveFileName:默认保存文件名defaultFileFmt:不指定saveFileName时,自动以此格式的时间字符串命名文件fileType:可以选择的文件类型return:(所选的文件保存路径, 文件的类型)"""options = QFileDialog.Option.ReadOnlyif saveFileName == '':saveFileName = self.sys_getCurTime(defaultFileFmt)if not saveFileDir:saveFileDir = self.dir_lastAccesssaveFilePath = os.path.join(saveFileDir, saveFileName)if not fileType:fileType = self.fileType_allfilePath, fileFormat = QFileDialog.getSaveFileName(widget, title, saveFilePath, fileType, options=options)if filePath:self.dir_lastAccess = os.path.dirname(filePath)return (filePath, fileFormat)class MainWindow(QMainWindow):def __init__(self):super(MainWindow, self).__init__()self.setWindowTitle('自定义截图工具展示')self.screenShotWg = ScreenShotWidget()centralLayout = QVBoxLayout()centralLayout.addWidget(QPushButton('开始截图', clicked=lambda: self.screenShot()))centralLayout.addWidget(QPushButton('隐藏本窗口后截图', clicked=lambda: self.screenShot(True)))centralWidget = QWidget()centralWidget.setLayout(centralLayout)self.setCentralWidget(centralWidget)def screenShot(self, hide=False):if hide:self.showMinimized()self.screenShotWg.start()if __name__ == '__main__':app = QApplication(sys.argv)translator = QtCore.QTranslator()  # 颜色选取窗口、字体选择窗口中文化# if translator.load("D:/dev/Python38/Lib/site-packages/PyQt6/Qt6/translations/qtbase_zh_CN.qm"):#     app.installTranslator(translator)main = MainWindow()main.show()sys.exit(app.exec())

qrcmd.py

qrcmd_menu_dict = {'添加结束符': {'回车CR': '^#SC^3030052','回车回车CRCR': '^#SC^3030054','回车换行CR LF': '^#SC^3030051','回车换行回车换行': '^#SC^3030055','跳格TAB': '^#SC^3030053','没有结束符': '^#SC^3030050',},'USB接口恢复出厂设置': {'第一步扫描': '>!0016000.','USB KBW键盘(第二步扫描)': '^#SC^3030011',},'扫描模式设置': {'自感应模式': '^#SC^2050209','连续扫描模式': '^#SC^2050204','按键/指令模式': '^#SC^2050200',},'RS232串口/TTL/485接口恢复出厂设置': {'第一步扫描': '>!0016000.','RS232串口/UART/TTL/485(第二步扫描)': '^#SC^3030010',},'波特率设置': {'9600bps': '^#SC^2090106','38400bps': '^#SC^2090108','19200bps': '^#SC^2090107','115200bps': '^#SC^209010A',},'常用设置码': {'Data Matrix正、反向均可读': '^#SC^30306B2','QR code正、反向均可读': '^#SC^3030672','一维码全局使能': '^#SC^3030111','二维码全局使能': '^#SC^3030501',},'网口/WiFi接口恢复出厂设置': {'第一步扫描': '>!0016000.','第二步扫描': '^#SC^3030010','第三步扫描': '^#SC^209010A',},'照明和瞄准': {'照明普通': '>!0010152.','无照明': '>!0010151.','照明常亮': '>!0010150.','瞄准普通': '>!0010162.','无瞄准': '>!0010161.','瞄准常亮': '>!0010160.',}
}

untitled.py

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt6 UI code generator 6.4.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic6 is
# run again.  Do not edit this file unless you know what you are doing.from PyQt6 import QtCore, QtGui, QtWidgetsclass Ui_MainWindow(object):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(484, 510)self.centralwidget = QtWidgets.QWidget(parent=MainWindow)self.centralwidget.setObjectName("centralwidget")self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)self.gridLayout.setObjectName("gridLayout")self.tabWidget = QtWidgets.QTabWidget(parent=self.centralwidget)self.tabWidget.setObjectName("tabWidget")self.read_qrcode_tab = QtWidgets.QWidget()self.read_qrcode_tab.setObjectName("read_qrcode_tab")self.gridLayout_3 = QtWidgets.QGridLayout(self.read_qrcode_tab)self.gridLayout_3.setObjectName("gridLayout_3")self.pushButton_screenshot = QtWidgets.QPushButton(parent=self.read_qrcode_tab)self.pushButton_screenshot.setObjectName("pushButton_screenshot")self.gridLayout_3.addWidget(self.pushButton_screenshot, 0, 0, 1, 1)self.label_screenshot = QtWidgets.QLabel(parent=self.read_qrcode_tab)self.label_screenshot.setText("")self.label_screenshot.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_screenshot.setObjectName("label_screenshot")self.gridLayout_3.addWidget(self.label_screenshot, 2, 0, 1, 1)self.textBrowser_show_decode_result = QtWidgets.QTextBrowser(parent=self.read_qrcode_tab)self.textBrowser_show_decode_result.setObjectName("textBrowser_show_decode_result")self.gridLayout_3.addWidget(self.textBrowser_show_decode_result, 3, 0, 1, 1)self.tabWidget.addTab(self.read_qrcode_tab, "")self.qr_creator_tab = QtWidgets.QWidget()self.qr_creator_tab.setObjectName("qr_creator_tab")self.gridLayout_2 = QtWidgets.QGridLayout(self.qr_creator_tab)self.gridLayout_2.setObjectName("gridLayout_2")self.comboBox_qrcmd_menu0 = QtWidgets.QComboBox(parent=self.qr_creator_tab)self.comboBox_qrcmd_menu0.setObjectName("comboBox_qrcmd_menu0")self.gridLayout_2.addWidget(self.comboBox_qrcmd_menu0, 1, 1, 1, 1)self.comboBox_qrcmd_menu1 = QtWidgets.QComboBox(parent=self.qr_creator_tab)self.comboBox_qrcmd_menu1.setObjectName("comboBox_qrcmd_menu1")self.gridLayout_2.addWidget(self.comboBox_qrcmd_menu1, 1, 2, 1, 1)self.pushButton_save = QtWidgets.QPushButton(parent=self.qr_creator_tab)self.pushButton_save.setMaximumSize(QtCore.QSize(16777215, 16777215))self.pushButton_save.setObjectName("pushButton_save")self.gridLayout_2.addWidget(self.pushButton_save, 1, 3, 1, 1)self.label_6 = QtWidgets.QLabel(parent=self.qr_creator_tab)self.label_6.setMaximumSize(QtCore.QSize(60, 16777215))self.label_6.setObjectName("label_6")self.gridLayout_2.addWidget(self.label_6, 1, 0, 1, 1)self.textEdit = QtWidgets.QTextEdit(parent=self.qr_creator_tab)self.textEdit.setMaximumSize(QtCore.QSize(16777215, 30))self.textEdit.setObjectName("textEdit")self.gridLayout_2.addWidget(self.textEdit, 0, 0, 1, 4)self.pic_label = QtWidgets.QLabel(parent=self.qr_creator_tab)self.pic_label.setText("")self.pic_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.pic_label.setObjectName("pic_label")self.gridLayout_2.addWidget(self.pic_label, 3, 0, 1, 4)self.tabWidget.addTab(self.qr_creator_tab, "")self.tab = QtWidgets.QWidget()self.tab.setObjectName("tab")self.gridLayout_4 = QtWidgets.QGridLayout(self.tab)self.gridLayout_4.setObjectName("gridLayout_4")self.textEdit_uart = QtWidgets.QTextEdit(parent=self.tab)self.textEdit_uart.setObjectName("textEdit_uart")self.gridLayout_4.addWidget(self.textEdit_uart, 15, 0, 1, 2)self.comboBox_DataBits = QtWidgets.QComboBox(parent=self.tab)self.comboBox_DataBits.setObjectName("comboBox_DataBits")self.gridLayout_4.addWidget(self.comboBox_DataBits, 7, 1, 1, 1)self.label = QtWidgets.QLabel(parent=self.tab)self.label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label.setObjectName("label")self.gridLayout_4.addWidget(self.label, 5, 0, 1, 1)self.textBrowser_uart_decode = QtWidgets.QTextBrowser(parent=self.tab)self.textBrowser_uart_decode.setObjectName("textBrowser_uart_decode")self.gridLayout_4.addWidget(self.textBrowser_uart_decode, 18, 0, 1, 2)self.checkBox_keyboard_enable = QtWidgets.QCheckBox(parent=self.tab)self.checkBox_keyboard_enable.setObjectName("checkBox_keyboard_enable")self.gridLayout_4.addWidget(self.checkBox_keyboard_enable, 13, 0, 1, 1)self.pushButton_uart_send = QtWidgets.QPushButton(parent=self.tab)self.pushButton_uart_send.setObjectName("pushButton_uart_send")self.gridLayout_4.addWidget(self.pushButton_uart_send, 12, 1, 1, 1)self.label_2 = QtWidgets.QLabel(parent=self.tab)self.label_2.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_2.setObjectName("label_2")self.gridLayout_4.addWidget(self.label_2, 6, 0, 1, 1)self.checkBox = QtWidgets.QCheckBox(parent=self.tab)self.checkBox.setChecked(False)self.checkBox.setObjectName("checkBox")self.gridLayout_4.addWidget(self.checkBox, 13, 1, 1, 1)self.pushButton_com_connect = QtWidgets.QPushButton(parent=self.tab)self.pushButton_com_connect.setCheckable(True)self.pushButton_com_connect.setAutoExclusive(True)self.pushButton_com_connect.setAutoDefault(False)self.pushButton_com_connect.setFlat(False)self.pushButton_com_connect.setObjectName("pushButton_com_connect")self.gridLayout_4.addWidget(self.pushButton_com_connect, 11, 0, 1, 1)self.label_8 = QtWidgets.QLabel(parent=self.tab)self.label_8.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_8.setObjectName("label_8")self.gridLayout_4.addWidget(self.label_8, 16, 0, 1, 2)self.label_5 = QtWidgets.QLabel(parent=self.tab)self.label_5.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_5.setObjectName("label_5")self.gridLayout_4.addWidget(self.label_5, 9, 0, 1, 1)self.pushButton_uart_refresh = QtWidgets.QPushButton(parent=self.tab)self.pushButton_uart_refresh.setObjectName("pushButton_uart_refresh")self.gridLayout_4.addWidget(self.pushButton_uart_refresh, 12, 0, 1, 1)self.label_4 = QtWidgets.QLabel(parent=self.tab)self.label_4.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_4.setObjectName("label_4")self.gridLayout_4.addWidget(self.label_4, 8, 0, 1, 1)self.label_3 = QtWidgets.QLabel(parent=self.tab)self.label_3.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_3.setObjectName("label_3")self.gridLayout_4.addWidget(self.label_3, 7, 0, 1, 1)self.comboBox_Parity = QtWidgets.QComboBox(parent=self.tab)self.comboBox_Parity.setObjectName("comboBox_Parity")self.gridLayout_4.addWidget(self.comboBox_Parity, 8, 1, 1, 1)self.textBrowser_uart_rawdata = QtWidgets.QTextBrowser(parent=self.tab)self.textBrowser_uart_rawdata.setObjectName("textBrowser_uart_rawdata")self.gridLayout_4.addWidget(self.textBrowser_uart_rawdata, 17, 0, 1, 2)self.comboBox_com_list = QtWidgets.QComboBox(parent=self.tab)self.comboBox_com_list.setObjectName("comboBox_com_list")self.gridLayout_4.addWidget(self.comboBox_com_list, 5, 1, 1, 1)self.comboBox_BaudRates = QtWidgets.QComboBox(parent=self.tab)self.comboBox_BaudRates.setObjectName("comboBox_BaudRates")self.gridLayout_4.addWidget(self.comboBox_BaudRates, 6, 1, 1, 1)self.label_7 = QtWidgets.QLabel(parent=self.tab)self.label_7.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)self.label_7.setObjectName("label_7")self.gridLayout_4.addWidget(self.label_7, 14, 0, 1, 2)self.pushButton_com_disconnect = QtWidgets.QPushButton(parent=self.tab)self.pushButton_com_disconnect.setCheckable(True)self.pushButton_com_disconnect.setChecked(True)self.pushButton_com_disconnect.setAutoExclusive(True)self.pushButton_com_disconnect.setDefault(False)self.pushButton_com_disconnect.setObjectName("pushButton_com_disconnect")self.gridLayout_4.addWidget(self.pushButton_com_disconnect, 11, 1, 1, 1)self.comboBox_StopBits = QtWidgets.QComboBox(parent=self.tab)self.comboBox_StopBits.setObjectName("comboBox_StopBits")self.gridLayout_4.addWidget(self.comboBox_StopBits, 9, 1, 1, 1)self.tabWidget.addTab(self.tab, "")self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(parent=MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 484, 22))self.menubar.setObjectName("menubar")MainWindow.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(parent=MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)self.tabWidget.setCurrentIndex(2)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "二维码小工具"))self.pushButton_screenshot.setText(_translate("MainWindow", "截图"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.read_qrcode_tab), _translate("MainWindow", "二维码/条形码解析"))self.pushButton_save.setText(_translate("MainWindow", "保存"))self.label_6.setText(_translate("MainWindow", "扫描仪指令"))self.textEdit.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><meta charset=\"utf-8\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"hr { height: 1px; border-width: 0; }\n"
"li.unchecked::marker { content: \"\\2610\"; }\n"
"li.checked::marker { content: \"\\2612\"; }\n"
"</style></head><body style=\" font-family:\'Microsoft YaHei UI\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">请输入要转化的文字</p></body></html>"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.qr_creator_tab), _translate("MainWindow", "二维码生成"))self.label.setText(_translate("MainWindow", "端口名"))self.checkBox_keyboard_enable.setText(_translate("MainWindow", "使能键盘输出"))self.pushButton_uart_send.setText(_translate("MainWindow", "发送"))self.label_2.setText(_translate("MainWindow", "波特率"))self.checkBox.setText(_translate("MainWindow", "是否自动回车"))self.pushButton_com_connect.setText(_translate("MainWindow", "连接"))self.label_8.setText(_translate("MainWindow", "接收数据"))self.label_5.setText(_translate("MainWindow", "停止位"))self.pushButton_uart_refresh.setText(_translate("MainWindow", "刷新"))self.label_4.setText(_translate("MainWindow", "校验位"))self.label_3.setText(_translate("MainWindow", "数据位"))self.label_7.setText(_translate("MainWindow", "输入框"))self.pushButton_com_disconnect.setText(_translate("MainWindow", "断开"))self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "串口调试助手"))

untitled.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>MainWindow</class><widget class="QMainWindow" name="MainWindow"><property name="geometry"><rect><x>0</x><y>0</y><width>484</width><height>510</height></rect></property><property name="windowTitle"><string>二维码小工具</string></property><widget class="QWidget" name="centralwidget"><layout class="QGridLayout" name="gridLayout"><item row="0" column="0"><widget class="QTabWidget" name="tabWidget"><property name="currentIndex"><number>2</number></property><widget class="QWidget" name="read_qrcode_tab"><attribute name="title"><string>二维码/条形码解析</string></attribute><layout class="QGridLayout" name="gridLayout_3"><item row="0" column="0"><widget class="QPushButton" name="pushButton_screenshot"><property name="text"><string>截图</string></property></widget></item><item row="2" column="0"><widget class="QLabel" name="label_screenshot"><property name="text"><string/></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="3" column="0"><widget class="QTextBrowser" name="textBrowser_show_decode_result"/></item></layout></widget><widget class="QWidget" name="qr_creator_tab"><attribute name="title"><string>二维码生成</string></attribute><layout class="QGridLayout" name="gridLayout_2"><item row="1" column="1"><widget class="QComboBox" name="comboBox_qrcmd_menu0"/></item><item row="1" column="2"><widget class="QComboBox" name="comboBox_qrcmd_menu1"/></item><item row="1" column="3"><widget class="QPushButton" name="pushButton_save"><property name="maximumSize"><size><width>16777215</width><height>16777215</height></size></property><property name="text"><string>保存</string></property></widget></item><item row="1" column="0"><widget class="QLabel" name="label_6"><property name="maximumSize"><size><width>60</width><height>16777215</height></size></property><property name="text"><string>扫描仪指令</string></property></widget></item><item row="0" column="0" colspan="4"><widget class="QTextEdit" name="textEdit"><property name="maximumSize"><size><width>16777215</width><height>30</height></size></property><property name="html"><string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;meta charset=&quot;utf-8&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
hr { height: 1px; border-width: 0; }
li.unchecked::marker { content: &quot;\2610&quot;; }
li.checked::marker { content: &quot;\2612&quot;; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Microsoft YaHei UI'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;请输入要转化的文字&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string></property></widget></item><item row="3" column="0" colspan="4"><widget class="QLabel" name="pic_label"><property name="text"><string/></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item></layout></widget><widget class="QWidget" name="tab"><attribute name="title"><string>串口调试助手</string></attribute><layout class="QGridLayout" name="gridLayout_4"><item row="15" column="0" colspan="2"><widget class="QTextEdit" name="textEdit_uart"/></item><item row="7" column="1"><widget class="QComboBox" name="comboBox_DataBits"/></item><item row="5" column="0"><widget class="QLabel" name="label"><property name="text"><string>端口名</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="18" column="0" colspan="2"><widget class="QTextBrowser" name="textBrowser_uart_decode"/></item><item row="13" column="0"><widget class="QCheckBox" name="checkBox_keyboard_enable"><property name="text"><string>使能键盘输出</string></property></widget></item><item row="12" column="1"><widget class="QPushButton" name="pushButton_uart_send"><property name="text"><string>发送</string></property></widget></item><item row="6" column="0"><widget class="QLabel" name="label_2"><property name="text"><string>波特率</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="13" column="1"><widget class="QCheckBox" name="checkBox"><property name="text"><string>是否自动回车</string></property><property name="checked"><bool>false</bool></property></widget></item><item row="11" column="0"><widget class="QPushButton" name="pushButton_com_connect"><property name="text"><string>连接</string></property><property name="checkable"><bool>true</bool></property><property name="autoExclusive"><bool>true</bool></property><property name="autoDefault"><bool>false</bool></property><property name="flat"><bool>false</bool></property></widget></item><item row="16" column="0" colspan="2"><widget class="QLabel" name="label_8"><property name="text"><string>接收数据</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="9" column="0"><widget class="QLabel" name="label_5"><property name="text"><string>停止位</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="12" column="0"><widget class="QPushButton" name="pushButton_uart_refresh"><property name="text"><string>刷新</string></property></widget></item><item row="8" column="0"><widget class="QLabel" name="label_4"><property name="text"><string>校验位</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="7" column="0"><widget class="QLabel" name="label_3"><property name="text"><string>数据位</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="8" column="1"><widget class="QComboBox" name="comboBox_Parity"/></item><item row="17" column="0" colspan="2"><widget class="QTextBrowser" name="textBrowser_uart_rawdata"/></item><item row="5" column="1"><widget class="QComboBox" name="comboBox_com_list"/></item><item row="6" column="1"><widget class="QComboBox" name="comboBox_BaudRates"/></item><item row="14" column="0" colspan="2"><widget class="QLabel" name="label_7"><property name="text"><string>输入框</string></property><property name="alignment"><set>Qt::AlignCenter</set></property></widget></item><item row="11" column="1"><widget class="QPushButton" name="pushButton_com_disconnect"><property name="text"><string>断开</string></property><property name="checkable"><bool>true</bool></property><property name="checked"><bool>true</bool></property><property name="autoExclusive"><bool>true</bool></property><property name="default"><bool>false</bool></property></widget></item><item row="9" column="1"><widget class="QComboBox" name="comboBox_StopBits"/></item></layout></widget></widget></item></layout></widget><widget class="QMenuBar" name="menubar"><property name="geometry"><rect><x>0</x><y>0</y><width>484</width><height>22</height></rect></property></widget><widget class="QStatusBar" name="statusbar"/></widget><resources/><connections/>
</ui>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/26125.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【递归+二叉树思想+搜索】 Alice and the Cake题解

Alice and the Cake题解 AC记录&#xff1a;记录-洛谷 题面翻译&#xff08;大概就是题目大意&#xff09; 执行恰好 n − 1 n-1 n−1 次操作&#xff0c;每次操作可以选择当前所有蛋糕中满足其重量 w ⩾ 2 w\geqslant 2 w⩾2 的一块&#xff0c;然后将其分为质量分别为 …

手机连接ESP8266的WIFI,进入内置网页,输入要显示的内容,在OLED显示屏上显示文本

连线 OLEDESP8266含义GNDGND地线VCC3V电源SCLD1时钟线SDAD2通信数据线 只支持英文信息的显示和数字。 #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h>#d…

5.大模型高效微调(PEFT)未来发展趋势

PEFT 主流技术分类 UniPELT 探索PEFT 大模型的统一框架&#xff08;2022&#xff09; UIUC 和Meta AI 研究人员发表的UniPELT 提出将不同的PEFT 方法模块化。 通过门控机制学习激活最适合当前数据或任务的方法&#xff0c;尤其是最常见的3大类PEFT 技术&#xff1a; Adapters…

事业单位——被逆袭篇

目录 一、结果 二、考试 三、时间 四、复习 五、总结 一、结果 图1&#xff1a;2024年浙江广播电视集团下属浙江省中波发射管理中心公开招聘笔面试结果 准考证号笔试面试总成绩排名备注107016070.866.48310702416555.44107134390.871.681入围107146869.869.08210715406454.…

征信受损,别再犯傻!

听说你的征信出了点小问题&#xff1f;别急&#xff0c;这事儿说大不大&#xff0c;但也不能掉以轻心。征信&#xff0c;说白了就是你借钱还钱的记录本&#xff0c;一旦它“花”了&#xff0c;借钱可就没那么轻松了。 先来说说这征信“花”了是咋回事 征信“花”了&#xff0c…

18.1 HTTP服务器-极简服务器、请求与响应

1. 极简服务器 大道至简。使用Go语言构建世界上最简单的HTTP服务器&#xff0c;仅需四行代码。 标准库的net/http包提供了多种用于创建HTTP服务器的方法&#xff0c;其中包括&#xff1a; http.HandleFunc("/", rootHandler) 第一参数&#xff1a;访问的url 第二…

【Linux】进程间通信之命名管道

&#x1f466;个人主页&#xff1a;Weraphael ✍&#x1f3fb;作者简介&#xff1a;目前正在学习c和算法 ✈️专栏&#xff1a;Linux &#x1f40b; 希望大家多多支持&#xff0c;咱一起进步&#xff01;&#x1f601; 如果文章有啥瑕疵&#xff0c;希望大佬指点一二 如果文章对…

109.网络游戏逆向分析与漏洞攻防-装备系统数据分析-商店与捨取窗口数据的处理

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 如果看不懂、不知道现在做的什么&#xff0c;那就跟着做完看效果 现在的代码都是依据数据包来写的&#xff0c;如果看不懂代码&#xff0c;就说明没看懂数据包…

【优选算法】详解target类求和问题(附总结)

目录 1.两数求和 题目&#xff1a; 算法思路&#xff1a; 代码&#xff1a; 2.&#xff01;&#xff01;&#xff01;三数之和 题目 算法思路&#xff1a; 代码&#xff1a; 3.四数字和 题目&#xff1a; 算法思路&#xff1a; 代码&#xff1a; 总结&易错点&…

用人工智能写2024年高考作文

目录 用人工智能写2024年高考作文 引用 一、2024年 新课标I卷 作文真题 AI写作范文 二、2024年 全国甲卷 作文真题 AI写作范文 三、2024年 新课标II卷 作文真题 AI写作范文 四、2024年 北京卷 作文真题一 AI写作范文 作文真题二 AI写作范文 作文真题三 AI写作…

php 混合xml js,html 代码报错 ,结束标签关闭, short_open_tag 的作用,php关闭文件结束判断

结束标签关闭, short_open_tag 的作用&#xff0c;php关闭文件结束判断 有时候我们我们会将php&#xff0c;xml&#xff0c;js&#xff0c;html 混合编写 php文件只要开始标签而不要结尾标签? 混合代码看代码 直接运行 yntax error, unexpected version (T_STRING) in php…

验证码识别接口、多种样式验证码识别接口、中英文验证码识别接口

验证码识别接口、多种样式验证码识别接口、中英文验证码识别接口 本文提供一个基于OCR和机器学习的验证码识别接口&#xff0c;能够识别较复杂的中文、英文验证码&#xff0c;在OCR的基础上针对验证码进行算法优化。本接口是收费的&#xff08;最低0.5分1次调用&#xff0c;试…

C语言详解(文件操作)2

Hi~&#xff01;这里是奋斗的小羊&#xff0c;很荣幸您能阅读我的文章&#xff0c;诚请评论指点&#xff0c;欢迎欢迎 ~~ &#x1f4a5;&#x1f4a5;个人主页&#xff1a;奋斗的小羊 &#x1f4a5;&#x1f4a5;所属专栏&#xff1a;C语言 &#x1f680;本系列文章为个人学习…

CSS id选择器

目录 任务描述 相关知识 id选择器 id选择器语法 类选择器与id选择器的区别 编程要求 任务描述 在本关中&#xff0c;你将通过id选择器的方式完成页面菜单栏样式布局&#xff0c;栏目导航等任务。 完成任务之后&#xff0c;基本页面效果如下&#xff1a; 动态效果如下&am…

IDEA:配置Golang的开发环境

1、下载&安装 进入GO的官网下载对应的GO 我们可以下载安装版&#xff0c;不过本人习惯下载解压版&#xff0c;这个因个人而异 2、配置环境变量 GOBIN : %GOROOT%\bin GOPATH : D:\MyGo 工作区间 GOROOT : D:\Program Files\Go GOJDK地址PATH: %GOBIN% ; %GOROOT%\bin ; …

生成性人工智能模型:行业和当局的机会和风险

1 目标受众和本文档目的 BSI&#xff08;德国联邦信息安全办公室&#xff09;通过本出版物面向考虑在其工作流程中使用生成性AI模型的公司和当局&#xff0c;以提高对这些模型的基本安全意识&#xff0c;并促进它们的安全使用。为此&#xff0c;除了机会外&#xff0c;它还突出…

Spring Boot整合Redis实现发布/订阅功能

&#x1f604; 19年之后由于某些原因断更了三年&#xff0c;23年重新扬帆起航&#xff0c;推出更多优质博文&#xff0c;希望大家多多支持&#xff5e; &#x1f337; 古之立大事者&#xff0c;不惟有超世之才&#xff0c;亦必有坚忍不拔之志 &#x1f390; 个人CSND主页——Mi…

Kimichat使用案例012:用Kimichat拆解雷军在小米汽车SU7发布会上的演讲技巧

文章目录 一、介绍二、输入内容三、输出内容四、继续追问五、继续回答六、讲解对比七、对比回答相似之处:不同之处:八、职场人士如何借鉴九、借鉴内容一、介绍 小米SU7发布会可以说是非常成功。雷军的演讲技巧是发布会成功的重要因素之一,很值得借鉴学习。 可以借助Kimichat…

git服务器gitblit安装

1、下载 Gitblit 2、下载完后解压&#xff1a; 3、配制&#xff1a; 保存&#xff0c;退出编辑。 4、运行cmd&#xff0c;启用gitblit。 5、根据运行后的提示&#xff0c;也就是我们之间设置的port9990打开&#xff1a; 输入admin,admin就可以登录&#xff0c;这个账号密码&a…

[大模型]GLM4-9B-chat Lora 微调

本节我们简要介绍如何基于 transformers、peft 等框架&#xff0c;对 LLaMA3-8B-Instruct 模型进行 Lora 微调。Lora 是一种高效微调方法&#xff0c;深入了解其原理可参见博客&#xff1a;知乎|深入浅出 Lora。 这个教程会在同目录下给大家提供一个 nodebook 文件&#xff0c…