QT: load .ui at run time

本文介绍如何使用Qt的QUiLoader类在运行时从.ui文件加载动态对话框,避免将.ui文件转换为C++代码。文中展示了如何创建对话框实例并获取其子组件。

Dynamic dialogs are dialogs that are created from Qt Designer .ui files at run-time. Instead of converting
the .ui file to C++ code using uic, we can load the file at run-time using the QUiLoader class:

 

QUiLoader uiLoader;
QFile file("sortdialog.ui");
QWidget *sortDialog = uiLoader.load(&file);
if (sortDialog) {
...
}

 

We can access the form's child widgets using QObject::findChild<T>():
QComboBox *primaryColumnCombo =
sortDialog->findChild<QComboBox *>("primaryColumnCombo");
if (primaryColumnCombo) {
...
}

import os import time from PySide2.QtWidgets import QApplication, QProgressBar, QTextBrowser, \ QFileDialog from PySide2.QtUiTools import QUiLoader from PySide2 import QtCore from auto_accounting import AutoAccounting class MainWindows: def __init__(self): self.ui = QUiLoader().load('./ui/auto_accounting.ui') self.ele_dir_path = "" self.fuel_dir_path = "" self.ui.import_electric.clicked.connect(self.import_electric_path) self.ui.import_fuel.clicked.connect(self.import_fuel_path) self.ui.start.clicked.connect(self.go_statics) @staticmethod def __tb_display(tb, word: str = '', middle: bool = True, clear: bool = True): if clear: tb.clear() if word: tb.append(word) if middle: tb.setAlignment(QtCore.Qt.AlignCenter) def import_electric_path(self): self.ele_dir_path = QFileDialog.getExistingDirectory(None, "选择充电发票路径", os.getcwd()) self.ele_dir_path = f"{self.ele_dir_path}/" self.__tb_display(tb=self.ui.electric_file_path_display, word=self.ele_dir_path, middle=False) def import_fuel_path(self): self.fuel_dir_path = QFileDialog.getExistingDirectory(None, "选择加油发票路径", os.getcwd()) self.fuel_dir_path = f"{self.fuel_dir_path}/" self.__tb_display(tb=self.ui.fuel_file_path_display, word=self.fuel_dir_path, middle=False) def go_statics(self): self.__tb_display(tb=self.ui.monitor, word="统计中...", middle=False) if not self.ele_dir_path and not self.fuel_dir_path: self.__tb_display(tb=self.ui.monitor, word="请至少添加一个路径!", middle=False) return False A = AutoAccounting(electric_path=self.ele_dir_path, fuel_path=self.fuel_dir_path) files_ck_res = A.bill_abstract() if files_ck_res: self.__tb_display(tb=self.ui.monitor, word="", middle=False) for file_ck_res in files_ck_res: words = file_ck_res[1]+file_ck_res[2] self.__tb_display(tb=self.ui.monitor, word=words, middle=False, clear=False) elif A.wrong_bills: print(A.wrong_bills) self.__tb_display(tb=self.ui.monitor, word="", middle=False) for wrong_bill in A.wrong_bills: self.__tb_display(tb=self.ui.monitor, word=wrong_bill, middle=False, clear=False) else: self.__tb_display(tb=self.ui.monitor, word="已完成发票统计!", middle=False) app = QApplication([]) stats = MainWindows() stats.ui.show() app.exec_() 为什么”统计中...“无法显示在monitor文本框内
最新发布
07-23
import sys from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog from ui_main_window import Ui_MainWindow class MainWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # 连接信号槽 self.ui.btn_select_model.clicked.connect(self.select_model) self.ui.btn_upload_image.clicked.connect(self.upload_image) self.ui.btn_start.clicked.connect(self.start_detection) self.ui.btn_pause.clicked.connect(self.pause_detection) # 初始化状态 self.model_loaded = False self.detection_running = False def select_model(self): path, _ = QFileDialog.getOpenFileName( self, "选择模型文件", "", "模型文件 (*.pt *.pth)") if path: self.ui.txt_model_path.setText(path) self.load_model(path) def upload_image(self): path, _ = QFileDialog.getOpenImageFile( self, "选择检测图片", "", "图像文件 (*.png *.jpg *.bmp)") if path: self.display_image(path) def load_model(self, model_path): # 深度学习模型加载逻辑 try: # 示例:PyTorch模型加载 # self.model = torch.load(model_path) self.model_loaded = True except Exception as e: self.show_error(f"模型加载失败: {str(e)}") def start_detection(self): if self.model_loaded: self.detection_running = True self.run_detection() def pause_detection(self): self.detection_running = False def run_detection(self): # 实现检测逻辑 if self.detection_running: # 调用模型进行推理 result = "焊缝合格率:98.5%" self.ui.txt_result.append(result) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())选择检测的图片并没有出现在我插入QGraphicsView用于显示图片的位置中,请帮我补充修改代码,在摁下选择的图片同时显现出来
04-03
import sys import cv2 import torch import torchvision from PySide6 import QtGui from PySide6.QtCore import Qt, QEvent from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QGraphicsPixmapItem, QGraphicsScene, QGraphicsView from PySide6.QtGui import QPixmap, QImage, QImageReader from ultralytics import YOLO from main_window import Ui_MainWindow class MainWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # 连接信号槽 self.ui.btn_select_model.clicked.connect(self.select_model) self.ui.btn_upload_image.clicked.connect(self.upload_image) self.ui.btn_start.clicked.connect(self.start_detection) # 初始化状态 self.model_loaded = False self.detection_running = False def select_model(self): path, _ = QFileDialog.getOpenFileName( self, "选择模型文件", "", "模型文件 (*.pt *.pth)") if path: self.ui.txt_model_path.setText(path) self.load_model(path) def upload_image(self): file_dialog = QFileDialog() image_path, _ = file_dialog.getOpenFileName(self, '选择图片', '', 'Images (*.png *.xpm *.jpg *.bmp)') self.image_path = image_path if image_path: # 在这里添加加载图片的逻辑,例如显示图片到label self.ui.txt_image_path.setText(image_path) pixmap = QtGui.QPixmap(image_path) self.ui.label_2.setPixmap(pixmap) self.ui.label_2.setScaledContents(True) def load_model(self): model_path, _ = QFileDialog.getOpenFileName( self, "选择模型文件", "", "Model Files (*.pth *.onnx *.h5)") if model_path: try: # 示例模型加载代码(需根据实际框架修改) import torch self.model = torch.load(model_path) print("模型加载成功") except Exception as e: print(f"模型加载失败: {str(e)}") def start_detection(self): if self.model_loaded: self.detection_running = True self.run_detection() def run_detection(self): if hasattr(self, 'current_image'): results = self.model.predict(self.current_image) self.show_results(results) def show_results(self, results): self.ui.label_3.setText("\n".join( f"缺陷类型:{res['class']} 置信度:{res['confidence']:.2f}" for res in results )) annotated_frame = results[0].plot() # 将图像数据转换为QImage格式 height, width, channel = annotated_frame.shape bytes_per_line = 3 * width qimage = QtGui.QImage(annotated_frame.data, width, height, bytes_per_line, QtGui.QImage.Format_RGB888) # 将QImage转换为QPixmap pixmap = QtGui.QPixmap.fromImage(qimage) # 都执行: self.ui.label_3.setPixmap(pixmap) self.ui.label_3.setScaledContents(True) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec()) 我在运行后弹出的窗口里,点开始检测,并没有出现检测后的图片,请帮我检查代码并进行修改形成完整代码后方便我运行
04-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值