如何在Python QT Designer中插入Web浏览器

4

我已经在QT Designer 5中创建了一个简单的用户界面,并希望包含一个显示网页的小部件。我使用以下代码来将ui文件与python一起使用:

from PyQt5 import uic, QtWidgets
import sys

app = QtWidgets.QApplication(sys.argv)
window = uic.loadUi("test.ui")
window.show()
sys.exit(app.exec_())

在QT Designer中似乎没有可以用来插入Web浏览器小部件的小部件,因此我正在寻找一种使用类或其他方法实现此功能并将小部件添加到已在Designer中创建的接口的小部件。

1个回答

5
一个简单的解决方案是使用 QWebEngineView,在我的情况下我可以在 Qt Designer 中找到它:

enter image description here

但如果你没有它,也没问题,因为可以升级一个小部件。在之前的回答中,我指出了如何使用QVideoWidget来实现,但在你的情况下,你只需要更改即可。
Promoted class name: QWebEngineView
Header file: PyQt5.QtWebEngineWidgets

test.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>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QVBoxLayout" name="verticalLayout">
   <item>
    <widget class="QWebEngineView" name="widget" native="true"/>
   </item>
  </layout>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QWebEngineView</class>
   <extends>QWidget</extends>
   <header>PyQt5.QtWebEngineWidgets</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

main.py

import os
import sys

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, uic

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    path_ui = os.path.join(os.path.dirname(__file__), "test.ui")
    window = uic.loadUi(path_ui)
    window.widget.load(QtCore.QUrl("https://stackoverflow.com/"))
    window.show()
    sys.exit(app.exec_())

太棒了,非常感谢!!!不过你是怎么学到这些东西的呢?我在拼凑文档方面遇到了困难,也没有找到任何易于理解的Pyqt教程。或者说这主要是对类的工作原理有很好的理解吗? - West
1
@West 我建议阅读Qt文档,虽然它是为C++编写的,但许多概念也适用于Python。另外一个建议是尝试理解。通过我提出的问题,我学到了更多,最终不仅查看PyQt的帖子,还会查看Qt的帖子,因为许多概念在PyQt中也适用。 - eyllanesc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接