PyQt5:如何在Qt Designer中将QWidget提升为QAxWidget
正确将QWidget提升为QAxWidget的步骤及代码修正
一、Qt Designer提升操作步骤
- 打开Qt Designer,拖入一个QWidget到目标界面
- 右键该QWidget,选择「提升为...」
- 在弹出的提升对话框中填写:
- 提升的类名称:直接填写
QAxWidget(无需自定义类名,这是PyQt原生控件类) - 头文件:填写
PyQt5.QtAxContainer(QAxWidget属于该模块)
- 提升的类名称:直接填写
- 点击「添加」按钮,再点击「提升」完成操作
二、修正后的代码示例
1. 修正后的.ui文件
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>Form</class> <widget class="QWidget" name="Form"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>993</width> <height>758</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <widget class="QAxWidget" name="widget" native="true"/> </item> </layout> </widget> <customwidgets> <customwidget> <class>QAxWidget</class> <extends>QWidget</extends> <header location="global">PyQt5.QtAxContainer</header> <container>1</container> </customwidget> </customwidgets> <resources/> <connections/> </ui>
2. 修正后的生成.py模块代码
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtAxContainer import QAxWidget class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(993, 758) self.horizontalLayout = QtWidgets.QHBoxLayout(Form) self.horizontalLayout.setObjectName("horizontalLayout") self.widget = QAxWidget(Form) self.widget.setObjectName("widget") self.horizontalLayout.addWidget(self.widget) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form"))
3. 修正后的主窗口代码
from PyQt5 import QtCore, QtGui, QtWidgets from view.container import Ui_Form import sys import urllib.parse import urllib.request class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_Form() self.ui.setupUi(self) self.ui.widget.setFocusPolicy(QtCore.Qt.StrongFocus) self.ui.widget.setControl("{8856F961-340A-11D0-A96B-00C04FD705A2}") pdf_path = r"C:\Users\isDev\Documents\ismael\respaldo\UrimareGUI\ReportLab\datasheet.pdf" uri = urllib.parse.urljoin('file:', urllib.request.pathname2url(pdf_path)) self.ui.widget.dynamicCall('Navigate(const QString&)', uri) if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() app.exec_()
三、错误原因说明
- 自定义类名
pdfViewer属于多余操作:QAxWidget是PyQt5.QtAxContainer下的原生控件类,直接使用原类名即可,无需自定义 - 导入路径错误:原代码尝试从
QAxWidget模块导入自定义类,但QAxWidget本身是类而非模块,正确导入应为from PyQt5.QtAxContainer import QAxWidget - 主窗口初始化遗漏:原代码未调用
setupUi方法初始化UI,导致控件对象未被创建
内容的提问来源于stack exchange,提问作者Ismael Santana
相关产品推荐
相关产品推荐

