QtWidgets Module's Classes

Qt Widgets C++ Classes

The Qt Widgets module extends Qt GUI with C++ widget functionality. More...

 

API Reference

These are links to the API reference materials.

 

 

Classes

QAbstractButton

The abstract base class of button widgets, providing functionality common to buttons

QAbstractGraphicsShapeItem

Common base for all path items

QAbstractItemDelegate

Used to display and edit data items from a model

QAbstractItemView

The basic functionality for item view classes

QAbstractScrollArea

Scrolling area with on-demand scroll bars

QAbstractSlider

Integer value within a range

QAbstractSpinBox

Spinbox and a line edit to display values

QAccessibleWidget

Implements the QAccessibleInterface for QWidgets

QAction

Abstract user interface action that can be inserted into widgets

QActionGroup

Groups actions together

QApplication

Manages the GUI application's control flow and main settings

QBoxLayout

Lines up child widgets horizontally or vertically

QButtonGroup

Container to organize groups of button widgets

QCalendarWidget

Monthly based calendar widget allowing the user to select a date

QCheckBox

Checkbox with a text label

QColorDialog

Dialog widget for specifying colors

QColormap

Maps device independent QColors to device dependent pixel values

QColumnView

Model/view implementation of a column view

QComboBox

Combined button and popup list

QCommandLinkButton

Vista style command link button

QCommonStyle

Encapsulates the common Look and Feel of a GUI

QCompleter

Completions based on an item model

QDataWidgetMapper

Mapping between a section of a data model to widgets

QDateEdit

Widget for editing dates based on the QDateTimeEdit widget

QDateTimeEdit

Widget for editing dates and times

QDesktopWidget

Access to screen information on multi-head systems

QDial

Rounded range control (like a speedometer or potentiometer)

QDialog

The base class of dialog windows

QDialogButtonBox

Widget that presents buttons in a layout that is appropriate to the current widget style

QDockWidget

Widget that can be docked inside a QMainWindow or floated as a top-level window on the desktop

QDoubleSpinBox

Spin box widget that takes doubles

QErrorMessage

Error message display dialog

QFileDialog

Dialog that allow users to select files or directories

QFileIconProvider

File icons for the QDirModel and the QFileSystemModel classes

QFileSystemModel

Data model for the local filesystem

QFocusFrame

Focus frame which can be outside of a widget's normal paintable area

QFontComboBox

Combobox that lets the user select a font family

QFontDialog

Dialog widget for selecting a font

QFormLayout

Manages forms of input widgets and their associated labels

QFrame

The base class of widgets that can have a frame

QGesture

Represents a gesture, containing properties that describe the corresponding user input

QGestureEvent

The description of triggered gestures

QGestureRecognizer

The infrastructure for gesture recognition

QGraphicsAnchor

Represents an anchor between two items in a QGraphicsAnchorLayout

QGraphicsAnchorLayout

Layout where one can anchor widgets together in Graphics View

QGraphicsBlurEffect

Blur effect

QGraphicsColorizeEffect

Colorize effect

QGraphicsDropShadowEffect

Drop shadow effect

QGraphicsEffect

The base class for all graphics effects

QGraphicsEllipseItem

Ellipse item that you can add to a QGraphicsScene

QGraphicsGridLayout

Grid layout for managing widgets in Graphics View

QGraphicsItem

The base class for all graphical items in a QGraphicsScene

QGraphicsItemGroup

Container that treats a group of items as a single item

QGraphicsLayout

The base class for all layouts in Graphics View

QGraphicsLayoutItem

Can be inherited to allow your custom items to be managed by layouts

QGraphicsLineItem

Line item that you can add to a QGraphicsScene

QGraphicsLinearLayout

Horizontal or vertical layout for managing widgets in Graphics View

QGraphicsObject

Base class for all graphics items that require signals, slots and properties

QGraphicsOpacityEffect

Opacity effect

QGraphicsPathItem

Path item that you can add to a QGraphicsScene

QGraphicsPixmapItem

Pixmap item that you can add to a QGraphicsScene

QGraphicsPolygonItem

Polygon item that you can add to a QGraphicsScene

QGraphicsProxyWidget

Proxy layer for embedding a QWidget in a QGraphicsScene

QGraphicsRectItem

Rectangle item that you can add to a QGraphicsScene

QGraphicsRotation

Rotation transformation around a given axis

QGraphicsScale

Scale transformation

QGraphicsScene

Surface for managing a large number of 2D graphical items

QGraphicsSceneContextMenuEvent

Context menu events in the graphics view framework

QGraphicsSceneDragDropEvent

Events for drag and drop in the graphics view framework

QGraphicsSceneEvent

Base class for all graphics view related events

QGraphicsSceneHelpEvent

Events when a tooltip is requested

QGraphicsSceneHoverEvent

Hover events in the graphics view framework

QGraphicsSceneMouseEvent

Mouse events in the graphics view framework

QGraphicsSceneMoveEvent

Events for widget moving in the graphics view framework

QGraphicsSceneResizeEvent

Events for widget resizing in the graphics view framework

QGraphicsSceneWheelEvent

Wheel events in the graphics view framework

QGraphicsSimpleTextItem

Simple text path item that you can add to a QGraphicsScene

QGraphicsTextItem

Text item that you can add to a QGraphicsScene to display formatted text

QGraphicsTransform

Abstract base class for building advanced transformations on QGraphicsItems

QGraphicsView

Widget for displaying the contents of a QGraphicsScene

QGraphicsWidget

The base class for all widget items in a QGraphicsScene

QGridLayout

Lays out widgets in a grid

QGroupBox

Group box frame with a title

QHBoxLayout

Lines up widgets horizontally

QHeaderView

Header row or header column for item views

QInputDialog

Simple convenience dialog to get a single value from the user

QItemDelegate

Display and editing facilities for data items from a model

QItemEditorCreator

Makes it possible to create item editor creator bases without subclassing QItemEditorCreatorBase

QItemEditorCreatorBase

Abstract base class that must be subclassed when implementing new item editor creators

QItemEditorFactory

Widgets for editing item data in views and delegates

QKeyEventTransition

Transition for key events

QKeySequenceEdit

Allows to input a QKeySequence

QLCDNumber

Displays a number with LCD-like digits

QLabel

Text or image display

QLayout

The base class of geometry managers

QLayoutItem

Abstract item that a QLayout manipulates

QLineEdit

One-line text editor

QListView

List or icon view onto a model

QListWidget

Item-based list widget

QListWidgetItem

Item for use with the QListWidget item view class

QMacCocoaViewContainer

Widget for Mac OS X that can be used to wrap arbitrary Cocoa views (i.e., NSView subclasses) and insert them into Qt hierarchies

QMacNativeWidget

Widget for Mac OS X that provides a way to put Qt widgets into Cocoa hierarchies

QMainWindow

Main application window

QMdiArea

Area in which MDI windows are displayed

QMdiSubWindow

Subwindow class for QMdiArea

QMenu

Menu widget for use in menu bars, context menus, and other popup menus

QMenuBar

Horizontal menu bar

QMessageBox

Modal dialog for informing the user or for asking the user a question and receiving an answer

QMouseEventTransition

Transition for mouse events

QOpenGLWidget

Widget for rendering OpenGL graphics

QPanGesture

Describes a panning gesture made by the user

QPinchGesture

Describes a pinch gesture made by the user

QPlainTextDocumentLayout

Implements a plain text layout for QTextDocument

QPlainTextEdit

Widget that is used to edit and display plain text

QProgressBar

Horizontal or vertical progress bar

QProgressDialog

Feedback on the progress of a slow operation

QProxyStyle

Convenience class that simplifies dynamically overriding QStyle elements

QPushButton

Command button

QRadioButton

Radio button with a text label

QRubberBand

Rectangle or line that can indicate a selection or a boundary

QScrollArea

Scrolling view onto another widget

QScrollBar

Vertical or horizontal scroll bar

QScroller

Enables kinetic scrolling for any scrolling widget or graphics item

QScrollerProperties

Stores the settings for a QScroller

QSessionManager

Access to the session manager

QShortcut

Used to create keyboard shortcuts

QSizeGrip

Resize handle for resizing top-level windows

QSizePolicy

Layout attribute describing horizontal and vertical resizing policy

QSlider

Vertical or horizontal slider

QSpacerItem

Blank space in a layout

QSpinBox

Spin box widget

QSplashScreen

Splash screen that can be shown during application startup

QSplitter

Implements a splitter widget

QSplitterHandle

Handle functionality for the splitter

QStackedLayout

Stack of widgets where only one widget is visible at a time

QStackedWidget

Stack of widgets where only one widget is visible at a time

QStandardItemEditorCreator

The possibility to register widgets without having to subclass QItemEditorCreatorBase

QStatusBar

Horizontal bar suitable for presenting status information

QStyle

Abstract base class that encapsulates the look and feel of a GUI

QStyleFactory

Creates QStyle objects

QStyleHintReturn

Style hints that return more than basic data types

QStyleHintReturnMask

Style hints that return a QRegion

QStyleHintReturnVariant

Style hints that return a QVariant

QStyleOption

Stores the parameters used by QStyle functions

QStyleOptionButton

Used to describe the parameters for drawing buttons

QStyleOptionComboBox

Used to describe the parameter for drawing a combobox

QStyleOptionComplex

Used to hold parameters that are common to all complex controls

QStyleOptionDockWidget

Used to describe the parameters for drawing a dock widget

QStyleOptionFocusRect

Used to describe the parameters for drawing a focus rectangle with QStyle

QStyleOptionFrame

Used to describe the parameters for drawing a frame

QStyleOptionGraphicsItem

Used to describe the parameters needed to draw a QGraphicsItem

QStyleOptionGroupBox

Describes the parameters for drawing a group box

QStyleOptionHeader

Used to describe the parameters for drawing a header

QStyleOptionMenuItem

Used to describe the parameter necessary for drawing a menu item

QStyleOptionProgressBar

Used to describe the parameters necessary for drawing a progress bar

QStyleOptionRubberBand

Used to describe the parameters needed for drawing a rubber band

QStyleOptionSizeGrip

Used to describe the parameter for drawing a size grip

QStyleOptionSlider

Used to describe the parameters needed for drawing a slider

QStyleOptionSpinBox

Used to describe the parameters necessary for drawing a spin box

QStyleOptionTab

Used to describe the parameters for drawing a tab bar

QStyleOptionTabBarBase

Used to describe the base of a tab bar, i.e. the part that the tab bar usually overlaps with

QStyleOptionTabWidgetFrame

Used to describe the parameters for drawing the frame around a tab widget

QStyleOptionTitleBar

Used to describe the parameters for drawing a title bar

QStyleOptionToolBar

Used to describe the parameters for drawing a toolbar

QStyleOptionToolBox

Used to describe the parameters needed for drawing a tool box

QStyleOptionToolButton

Used to describe the parameters for drawing a tool button

QStyleOptionViewItem

Used to describe the parameters used to draw an item in a view widget

QStylePainter

Convenience class for drawing QStyle elements inside a widget

QStylePlugin

Abstract base for custom QStyle plugins

QStyledItemDelegate

Display and editing facilities for data items from a model

QSwipeGesture

Describes a swipe gesture made by the user

QSystemTrayIcon

Icon for an application in the system tray

QTabBar

Tab bar, e.g. for use in tabbed dialogs

QTabWidget

Stack of tabbed widgets

QTableView

Default model/view implementation of a table view

QTableWidget

Item-based table view with a default model

QTableWidgetItem

Item for use with the QTableWidget class

QTableWidgetSelectionRange

Way to interact with selection in a model without using model indexes and a selection model

QTapAndHoldGesture

Describes a tap-and-hold (aka LongTap) gesture made by the user

QTapGesture

Describes a tap gesture made by the user

QTextBrowser

Rich text browser with hypertext navigation

QTextEdit

Widget that is used to edit and display both plain and rich text

QTextEdit::ExtraSelection

QTextEdit::ExtraSelection structure provides a way of specifying a character format for a given selection in a document

QTileRules

The rules used to draw a pixmap or image split into nine segments

QTimeEdit

Widget for editing times based on the QDateTimeEdit widget

QToolBar

Movable panel that contains a set of controls

QToolBox

Column of tabbed widget items

QToolButton

Quick-access button to commands or options, usually used inside a QToolBar

QToolTip

Tool tips (balloon help) for any widget

QTreeView

Default model/view implementation of a tree view

QTreeWidget

Tree view that uses a predefined tree model

QTreeWidgetItem

Item for use with the QTreeWidget convenience class

QTreeWidgetItemIterator

Way to iterate over the items in a QTreeWidget instance

QUndoCommand

The base class of all commands stored on a QUndoStack

QUndoGroup

Group of QUndoStack objects

QUndoStack

Stack of QUndoCommand objects

QUndoView

Displays the contents of a QUndoStack

QVBoxLayout

Lines up widgets vertically

QWhatsThis

Simple description of any widget, i.e. answering the question "What's This?"

QWidget

The base class of all user interface objects

QWidgetAction

Extends QAction by an interface for inserting custom widgets into action based containers, such as toolbars

QWidgetItem

Layout item that represents a widget

QWizard

Framework for wizards

QWizardPage

The base class for wizard pages

 

from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenu, QAction from ui.win import Ui_mainWindow from PyQt5.QtCore import Qt, QPoint, QTimer, QThread, pyqtSignal from PyQt5.QtGui import QImage, QPixmap, QPainter, QIcon import sys import os import json import numpy as np import torch import torch.backends.cudnn as cudnn import os import time import cv2 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) from models.experimental import attempt_load from utils.datasets import LoadImages, LoadWebcam from utils.CustomMessageBox import MessageBox from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path # from utils.plots import colors, plot_one_box, plot_one_box_PIL from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device from utils.capnums import Camera from deep_sort.deep_sort import DeepSort def deepsort_update(Tracker, pred, xywh, np_img): outputs = Tracker.update(xywh, pred[:, 4:5], pred[:, 5].tolist(), cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB)) return outputs class DetThread(QThread): send_img = pyqtSignal(np.ndarray) send_raw = pyqtSignal(np.ndarray) send_statistic = pyqtSignal(dict) send_msg = pyqtSignal(str) send_percent = pyqtSignal(int) send_fps = pyqtSignal(str) def __init__(self,tracker = &#39;ByteTrack&#39;,imgsz=(640,640)): super(DetThread, self).__init__() self.weights = &#39;./yolov5s.pt&#39; self.current_weight = &#39;./yolov5s.pt&#39; self.source = &#39;0&#39; self.conf_thres = 0.25 self.iou_thres = 0.45 self.jump_out = False # jump out of the loop self.is_continue = True # continue/pause self.percent_length = 1000 # progress bar self.rate_check = True # Whether to enable delay self.rate = 100 self.imgsz = check_img_size(imgsz) self.save_fold = &#39;./result&#39; if tracker == &#39;DeepSort&#39;: self.tracker = DeepSort(&#39;deep_sort/deep_sort/deep/checkpoint/ckpt_car3.t7&#39;) self._type = &#39;DeepSort&#39; @torch.no_grad() def run(self, imgsz=640, max_det=1000, # maximum detections per image device=&#39;&#39;, # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=True, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=&#39;runs/detect&#39;, # save results to project/name name=&#39;exp&#39;, # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference ): # 初始化 try: # 选择设备(如CPU或GPU) device = select_device(device) # 如果设备不是CPU,设置half为True以使用半精度浮点数 half &= device.type != &#39;cpu&#39; # 尝试加载模型,并将模型加载到指定设备上 model = attempt_load(self.weights, map_location=device) num_params = 0 # 计算模型参数的总数 for param in model.parameters(): num_params += param.numel() # 获取模型的步幅(stride),并确保图像尺寸是步幅的倍数 stride = int(model.stride.max()) imgsz = check_img_size(imgsz, s=stride) # 获取模型的类别名称 names = model.module.names if hasattr(model, &#39;module&#39;) else model.names # 如果使用半精度浮点数,转换模型的权重为半精度 if half: model.half() # 如果使用CUDA设备,进行一次空推理以初始化模型 if device.type != &#39;cpu&#39;: model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) deepsort_tracker = DeepSort(&#39;deep_sort/deep_sort/deep/checkpoint/ckpt_car3.t7&#39;) # 数据加载 if self.source.isnumeric() or self.source.lower().startswith((&#39;rtsp://&#39;, &#39;rtmp://&#39;, &#39;http://&#39;, &#39;https://&#39;)): view_img = check_imshow() cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadWebcam(self.source, img_size=imgsz, stride=stride) # bs = len(dataset) # batch_size else: dataset = LoadImages(self.source, img_size=imgsz, stride=stride) #根据输入源(视频流或本地图片/视频)加载数据。如果是视频流,启用 cudnn.benchmark 以加速推理 count = 0 jump_count = 0 start_time = time.time() dataset = iter(dataset) #主循环 while True: if self.jump_out: self.vid_cap.release() self.send_percent.emit(0) self.send_msg.emit(&#39;停止&#39;) if hasattr(self, &#39;out&#39;): self.out.release() break #主循环处理每一帧数据。如果接收到跳出信号,则释放资源并退出循环 # 更换模型 # 如果当前权重与新权重不一致,更新模型 if self.current_weight != self.weights: # 加载模型 model = attempt_load(self.weights, map_location=device) # 加载FP32模型(32位浮点数) num_params = 0 # 计算模型参数总数 for param in model.parameters(): num_params += param.numel() # 获取模型步幅(stride) stride = int(model.stride.max()) # 检查图像尺寸是否为步幅的整数倍 imgsz = check_img_size(imgsz, s=stride) # 获取模型的类别名称 names = model.module.names if hasattr(model, &#39;module&#39;) else model.names # 如果使用半精度浮点数,转换模型权重为FP16(16位浮点数) if half: model.half() # 如果设备不是CPU,运行一次模型以完成初始化 if device.type != &#39;cpu&#39;: model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # 更新当前权重 self.current_weight = self.weights #如果检测到模型权重发生改变,重新加载模型。 #数据预处理 # 如果继续处理标志位为True,则执行以下代码 if self.is_continue: # 从数据集中获取下一帧数据,包括路径、图像、原始图像和视频捕获对象 path, img, im0s, self.vid_cap = next(dataset) count += 1 # 帧计数器加一 # 每处理30帧,计算一次FPS(帧率) if count % 30 == 0 and count >= 30: fps = int(30 / (time.time() - start_time)) # 计算30帧处理所需时间的平均FPS self.send_fps.emit(&#39;fps:&#39; + str(fps)) # 发送FPS信号 start_time = time.time() # 重新记录开始时间 # 如果有视频捕获对象,计算视频处理进度百分比 if self.vid_cap: percent = int(count / self.vid_cap.get(cv2.CAP_PROP_FRAME_COUNT) * self.percent_length) self.send_percent.emit(percent) # 发送进度百分比信号 else: percent = self.percent_length # 如果没有视频捕获对象,设定进度为满 # 初始化统计字典,统计每个类别的数量 statistic_dic = {name: 0 for name in names} # 将图像从numpy数组转换为torch张量,并加载到指定设备(如GPU) img = torch.from_numpy(img).to(device) # 如果使用半精度浮点数,转换图像数据类型,否则转换为浮点数 img = img.half() if half else img.float() # uint8 to fp16/32 img /= 255.0 # 将像素值从0-255归一化到0.0-1.0 # 如果图像是三维的,增加一个维度以匹配模型输入要求 if img.ndimension() == 3: img = img.unsqueeze(0) # 推理 pred = model(img, augment=augment)[0] #NMS pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes, agnostic_nms, max_det=max_det) # 处理检测结果 迭代每个检测结果,并绘制边界框和标签 # 遍历每张图像的检测结果 for i, det in enumerate(pred): # detections per image # 复制原始图像,以便在上面绘制标注 im0 = im0s.copy() # 创建一个Annotator对象,用于在图像上绘制标注 annotator = Annotator(im0, line_width=line_thickness, example=str(names)) # 如果有检测结果 if len(det): # 将检测框的坐标从img_size尺度重新缩放到原始图像尺度,并四舍五入 det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # 进行目标跟踪 track_outputs = deepsort_update(deepsort_tracker, det.cpu(), det[:, :4].cpu(), im0) # Write results # for *xyxy, conf, cls in reversed(det): # c = int(cls) # integer class # statistic_dic[names[c]] += 1 # label = None if hide_labels else (names[c] if hide_conf else f&#39;{names[c]} {conf:.2f}&#39;) # annotator.box_label(xyxy, label, color=colors(c, True)) # 将跟踪结果绘制到图片上 if len(track_outputs)>0: for track_output in track_outputs: xyxy = track_output[:4] c = int(track_output[4]) # integer class track_id = &#39;ID_&#39; + str(track_output[5]) statistic_dic[names[c]] += 1 label = (f&#39;{track_id}&#39;) if hide_labels else (f&#39;{track_id} {names[c]}&#39;) annotator.box_label(xyxy, label, color=colors(c, True)) if self.rate_check: time.sleep(1/self.rate) #保存检测结果图像或视频,并通过信号发送处理后的图像和统计数据 im0 = annotator.result() self.send_img.emit(im0) self.send_raw.emit(im0s if isinstance(im0s, np.ndarray) else im0s[0]) self.send_statistic.emit(statistic_dic) if self.save_fold: os.makedirs(self.save_fold, exist_ok=True) if self.vid_cap is None: save_path = os.path.join(self.save_fold, time.strftime(&#39;%Y_%m_%d_%H_%M_%S&#39;, time.localtime()) + &#39;.jpg&#39;) cv2.imwrite(save_path, im0) else: if count == 1: ori_fps = int(self.vid_cap.get(cv2.CAP_PROP_FPS)) if ori_fps == 0: ori_fps = 25 # width = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # height = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) width, height = im0.shape[1], im0.shape[0] save_path = os.path.join(self.save_fold, time.strftime(&#39;%Y_%m_%d_%H_%M_%S&#39;, time.localtime()) + &#39;.mp4&#39;) self.out = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), ori_fps, (width, height)) self.out.write(im0) if percent == self.percent_length: print(count) self.send_percent.emit(0) self.send_msg.emit(&#39;结束&#39;) if hasattr(self, &#39;out&#39;): self.out.release() break except Exception as e: self.send_msg.emit(&#39;%s&#39; % e) class MainWindow(QMainWindow, Ui_mainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.m_flag = False # style 1: window can be stretched # self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint) # style 2: window can not be stretched self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint) # self.setWindowOpacity(0.85) # Transparency of window self.minButton.clicked.connect(self.showMinimized) self.maxButton.clicked.connect(self.max_or_restore) # show Maximized window self.maxButton.animateClick(10) self.closeButton.clicked.connect(self.close) self.qtimer = QTimer(self) self.qtimer.setSingleShot(True) self.qtimer.timeout.connect(lambda: self.statistic_label.clear()) # search models automatically self.comboBox.clear() self.pt_list = os.listdir(&#39;./pt&#39;) self.pt_list = [file for file in self.pt_list if file.endswith(&#39;.pt&#39;)] self.pt_list.sort(key=lambda x: os.path.getsize(&#39;./pt/&#39;+x)) self.comboBox.clear() self.comboBox.addItems(self.pt_list) self.qtimer_search = QTimer(self) self.qtimer_search.timeout.connect(lambda: self.search_pt()) self.qtimer_search.start(2000) # yolov5 thread self.det_thread = DetThread() self.model_type = self.comboBox.currentText() self.det_thread.weights = "./pt/%s" % self.model_type self.det_thread.source = &#39;0&#39; self.det_thread.percent_length = self.progressBar.maximum() self.det_thread.send_raw.connect(lambda x: self.show_image(x, self.raw_video)) self.det_thread.send_img.connect(lambda x: self.show_image(x, self.out_video)) self.det_thread.send_statistic.connect(self.show_statistic) self.det_thread.send_msg.connect(lambda x: self.show_msg(x)) self.det_thread.send_percent.connect(lambda x: self.progressBar.setValue(x)) self.det_thread.send_fps.connect(lambda x: self.fps_label.setText(x)) self.fileButton.clicked.connect(self.open_file) self.cameraButton.clicked.connect(self.chose_cam) #self.rtspButton.clicked.connect(self.chose_rtsp) self.runButton.clicked.connect(self.run_or_continue) self.stopButton.clicked.connect(self.stop) self.comboBox.currentTextChanged.connect(self.change_model) self.confSpinBox.valueChanged.connect(lambda x: self.change_val(x, &#39;confSpinBox&#39;)) self.confSlider.valueChanged.connect(lambda x: self.change_val(x, &#39;confSlider&#39;)) self.iouSpinBox.valueChanged.connect(lambda x: self.change_val(x, &#39;iouSpinBox&#39;)) self.iouSlider.valueChanged.connect(lambda x: self.change_val(x, &#39;iouSlider&#39;)) self.rateSpinBox.valueChanged.connect(lambda x: self.change_val(x, &#39;rateSpinBox&#39;)) self.rateSlider.valueChanged.connect(lambda x: self.change_val(x, &#39;rateSlider&#39;)) self.checkBox.clicked.connect(self.checkrate) self.saveCheckBox.clicked.connect(self.is_save) self.load_setting() def search_pt(self): pt_list = os.listdir(&#39;./pt&#39;) pt_list = [file for file in pt_list if file.endswith(&#39;.pt&#39;)] pt_list.sort(key=lambda x: os.path.getsize(&#39;./pt/&#39; + x)) if pt_list != self.pt_list: self.pt_list = pt_list self.comboBox.clear() self.comboBox.addItems(self.pt_list) def is_save(self): if self.saveCheckBox.isChecked(): self.det_thread.save_fold = &#39;./result&#39; else: self.det_thread.save_fold = None def checkrate(self): if self.checkBox.isChecked(): self.det_thread.rate_check = True else: self.det_thread.rate_check = False def chose_cam(self): try: self.stop() MessageBox( self.closeButton, title=&#39;提示&#39;, text=&#39;加载摄像头&#39;, time=2000, auto=True).exec_() # get the number of local cameras _, cams = Camera().get_cam_num() popMenu = QMenu() popMenu.setFixedWidth(self.cameraButton.width()) popMenu.setStyleSheet(&#39;&#39;&#39; QMenu { font-size: 16px; font-family: "Microsoft YaHei UI"; font-weight: light; color:white; padding-left: 5px; padding-right: 5px; padding-top: 4px; padding-bottom: 4px; border-style: solid; border-width: 0px; border-color: rgba(255, 255, 255, 255); border-radius: 3px; background-color: rgba(200, 200, 200,50);} &#39;&#39;&#39;) for cam in cams: exec("action_%s = QAction(&#39;%s&#39;)" % (cam, cam)) exec("popMenu.addAction(action_%s)" % cam) x = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).x() y = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).y() y = y + self.cameraButton.frameGeometry().height() pos = QPoint(x, y) action = popMenu.exec_(pos) if action: self.det_thread.source = action.text() self.statistic_msg(&#39;加载视频:{}&#39;.format(action.text())) except Exception as e: self.statistic_msg(&#39;%s&#39; % e) def load_setting(self): config_file = &#39;config/setting.json&#39; if not os.path.exists(config_file): iou = 0.26 conf = 0.33 rate = 10 check = 0 savecheck = 0 new_config = {"iou": iou, "conf": conf, "rate": rate, "check": check, "savecheck": savecheck } new_json = json.dumps(new_config, ensure_ascii=False, indent=2) with open(config_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f: f.write(new_json) else: config = json.load(open(config_file, &#39;r&#39;, encoding=&#39;utf-8&#39;)) if len(config) != 5: iou = 0.26 conf = 0.33 rate = 10 check = 0 savecheck = 0 else: iou = config[&#39;iou&#39;] conf = config[&#39;conf&#39;] rate = config[&#39;rate&#39;] check = config[&#39;check&#39;] savecheck = config[&#39;savecheck&#39;] self.confSpinBox.setValue(conf) self.iouSpinBox.setValue(iou) self.rateSpinBox.setValue(rate) self.checkBox.setCheckState(check) self.det_thread.rate_check = check self.saveCheckBox.setCheckState(savecheck) self.is_save() def change_val(self, x, flag): if flag == &#39;confSpinBox&#39;: self.confSlider.setValue(int(x*100)) elif flag == &#39;confSlider&#39;: self.confSpinBox.setValue(x/100) self.det_thread.conf_thres = x/100 elif flag == &#39;iouSpinBox&#39;: self.iouSlider.setValue(int(x*100)) elif flag == &#39;iouSlider&#39;: self.iouSpinBox.setValue(x/100) self.det_thread.iou_thres = x/100 elif flag == &#39;rateSpinBox&#39;: self.rateSlider.setValue(x) elif flag == &#39;rateSlider&#39;: self.rateSpinBox.setValue(x) self.det_thread.rate = x * 10 else: pass def statistic_msg(self, msg): self.statistic_label.setText(msg) # self.qtimer.start(3000) def show_msg(self, msg): self.runButton.setChecked(Qt.Unchecked) self.statistic_msg(msg) if msg == "Finished": self.saveCheckBox.setEnabled(True) def change_model(self, x): self.model_type = self.comboBox.currentText() self.det_thread.weights = "./pt/%s" % self.model_type self.statistic_msg(&#39;Change model to %s&#39; % x) def open_file(self): config_file = &#39;config/fold.json&#39; # config = json.load(open(config_file, &#39;r&#39;, encoding=&#39;utf-8&#39;)) config = json.load(open(config_file, &#39;r&#39;, encoding=&#39;utf-8&#39;)) open_fold = config[&#39;open_fold&#39;] if not os.path.exists(open_fold): open_fold = os.getcwd() name, _ = QFileDialog.getOpenFileName(self, &#39;Video/image&#39;, open_fold, "Pic File(*.mp4 *.mkv *.avi *.flv " "*.jpg *.png)") if name: self.det_thread.source = name self.statistic_msg(&#39;Loaded file:{}&#39;.format(os.path.basename(name))) config[&#39;open_fold&#39;] = os.path.dirname(name) config_json = json.dumps(config, ensure_ascii=False, indent=2) with open(config_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f: f.write(config_json) self.stop() def max_or_restore(self): if self.maxButton.isChecked(): self.showMaximized() else: self.showNormal() def run_or_continue(self): self.det_thread.jump_out = False if self.runButton.isChecked(): self.saveCheckBox.setEnabled(False) self.det_thread.is_continue = True if not self.det_thread.isRunning(): self.det_thread.start() source = os.path.basename(self.det_thread.source) source = &#39;camera&#39; if source.isnumeric() else source self.statistic_msg(&#39;正在检测 >> 模型:{},文件:{}&#39;. format(os.path.basename(self.det_thread.weights), source)) else: self.det_thread.is_continue = False self.statistic_msg(&#39;暂停&#39;) def stop(self): self.det_thread.jump_out = True self.saveCheckBox.setEnabled(True) def mousePressEvent(self, event): self.m_Position = event.pos() if event.button() == Qt.LeftButton: if 0 < self.m_Position.x() < self.groupBox.pos().x() + self.groupBox.width() and \ 0 < self.m_Position.y() < self.groupBox.pos().y() + self.groupBox.height(): self.m_flag = True def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.m_flag: self.move(QMouseEvent.globalPos() - self.m_Position) def mouseReleaseEvent(self, QMouseEvent): self.m_flag = False @staticmethod def show_image(img_src, label): try: ih, iw, _ = img_src.shape w = label.geometry().width() h = label.geometry().height() # keep original aspect ratio if iw/w > ih/h: scal = w / iw nw = w nh = int(scal * ih) img_src_ = cv2.resize(img_src, (nw, nh)) else: scal = h / ih nw = int(scal * iw) nh = h img_src_ = cv2.resize(img_src, (nw, nh)) frame = cv2.cvtColor(img_src_, cv2.COLOR_BGR2RGB) img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1], QImage.Format_RGB888) label.setPixmap(QPixmap.fromImage(img)) except Exception as e: print(repr(e)) def show_statistic(self, statistic_dic): try: self.resultWidget.clear() statistic_dic = sorted(statistic_dic.items(), key=lambda x: x[1], reverse=True) statistic_dic = [i for i in statistic_dic if i[1] > 0] results = [&#39; &#39;+str(i[0]) + &#39;:&#39; + str(i[1]) for i in statistic_dic] self.resultWidget.addItems(results) except Exception as e: print(repr(e)) def closeEvent(self, event): self.det_thread.jump_out = True config_file = &#39;config/setting.json&#39; config = dict() config[&#39;iou&#39;] = self.confSpinBox.value() config[&#39;conf&#39;] = self.iouSpinBox.value() config[&#39;rate&#39;] = self.rateSpinBox.value() config[&#39;check&#39;] = self.checkBox.checkState() config[&#39;savecheck&#39;] = self.saveCheckBox.checkState() config_json = json.dumps(config, ensure_ascii=False, indent=2) with open(config_file, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f: f.write(config_json) MessageBox( self.closeButton, title=&#39;提示&#39;, text=&#39;正在关闭程序&#39;, time=2000, auto=True).exec_() sys.exit(0) if __name__ == "__main__": app = QApplication(sys.argv) myWin = MainWindow() myWin.show() # myWin.showMaximized() sys.exit(app.exec_())
05-30
<think>我们正在解决PyQt5中无法找到QFont属性的问题。根据用户描述,错误可能是类似"AttributeError:module&#39;PyQt5.QtWidgets&#39;hasnoattribute&#39;QFont&#39;"这样的错误。首先,我们需要明确QFont在PyQt5中的正确位置。在PyQt5中,QFont并不在QtWidgets模块中,而是在QtGui模块中。因此,正确的导入方式应该是:fromPyQt5.QtGuiimportQFont用户可能错误地从QtWidgets中导入QFont,导致出现属性错误。参考已有的引用信息,特别是引用[1]和引用[4]中的类似问题,我们可以知道这类错误通常是由于导入路径变化或命名冲突导致的。解决方案:1.检查导入语句,确保从正确的模块导入QFont。2.确保没有将当前文件命名为与PyQt5相关的名称(如PyQt5.py),这会导致导入冲突(如引用[4]所述)。3.检查环境是否安装正确,确保PyQt5包完整。因此,用户应该将导入语句改为:fromPyQt5.QtGuiimportQFont如果问题仍然存在,则检查文件名是否与PyQt5冲突,或者尝试重新安装PyQt5。下面是一个使用QFont的示例代码片段:```pythonfromPyQt5.QtWidgetsimportQApplication,QLabelfromPyQt5.QtGuiimportQFontapp=QApplication([])label=QLabel("Hello,World!")#设置字体font=QFont("Arial",16,QFont.Bold)label.setFont(font)label.show()app.exec_()```在这个示例中,我们从QtGui导入了QFont,并创建了一个字体对象,然后将其应用到一个标签上。如果用户按照上述步骤操作,应该可以解决QFont属性错误的问题。根据要求,生成相关问题:§§相关问题§§1.PyQt5中还有哪些常见的模块,它们分别包含哪些类?2.如何解决PyQt5中的其他常见导入错误?3.在PyQt5中如何设置字体的颜色和大小?4.PyQt5中的QFont类支持哪些字体属性设置?</think>### PyQt5中无法找到QFont属性的解决方案 在PyQt5中遇到`QFont`属性错误(如`AttributeError: module &#39;PyQt5.QtWidgets&#39; has no attribute &#39;QFont&#39;`)通常是由于**模块导入路径错误**导致的。以下是完整的解决步骤: #### 问题原因分析 1. **模块位置错误**:`QFont`类实际位于`PyQt5.QtGui`模块中,而不是`PyQt5.QtWidgets`模块[^1][^2]。 2. **文件命名冲突**:如果当前Python文件命名为`PyQt5.py`,会导致导入路径冲突(引用[4]描述的典型错误)[^4]。 3. **安装不完整**:PyQt5包可能未完整安装或版本不兼容。 #### 解决方案 **1. 修正导入路径(关键步骤)** ```python # 错误导入方式(导致属性错误) from PyQt5.QtWidgets import QFont # ❌ # 正确导入方式 ✅ from PyQt5.QtGui import QFont ``` **2. 检查文件命名** - 确保当前Python文件名**不是**`PyQt5.py`或`QtGui.py`等冲突名称 - 建议重命名文件为`my_app.py`等中性名称(引用[4])[^4] **3. 完整代码示例** ```python import sys from PyQt5.QtWidgets import QApplication, QLabel from PyQt5.QtGui import QFont # 正确导入位置 app = QApplication(sys.argv) label = QLabel("Hello PyQt5") # 创建字体对象 font = QFont("Arial", 16, QFont.Bold) # ✅ 现在可正常使用 label.setFont(font) label.show() sys.exit(app.exec_()) ``` **4. 环境验证(可选)** - 重新安装PyQt5: ```bash pip uninstall PyQt5 pip install PyQt5 ``` - 检查安装完整性: ```python import PyQt5 print(PyQt5.__version__) # 应输出版本号如5.15.2 ``` #### 关键原理 - PyQt5模块结构遵循Qt框架设计: - `QtWidgets`:包含UI组件(如按钮、文本框)[^2] - `QtGui`:包含图形相关类(字体、画笔、颜色等)[^1] - 所有GUI应用必须创建`QApplication`实例(引用[3])[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值