用QWebView显示PDF文件
我想在Pyside中显示一个带有QwebView小部件的窗口。为此,我使用了一些QtCreator生成的代码:
#code generated by QtCreator:
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.webView = QtWebKit.QWebView(self.centralWidget)
self.webView.setGeometry(QtCore.QRect(10, 20, 380, 270))
self.webView.setUrl(QtCore.QUrl("file:///C:/pdf_folder/test.pdf"))
self.webView.setObjectName("webView")
MainWindow.setCentralWidget(self.centralWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
from PySide import QtWebKit
# My code:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
APP = QtGui.QApplication(sys.argv)
MW = MainWindow()
MW.show()
sys.exit(APP.exec_())
我确定在指定的路径下有一个pdf文件,但当我运行我的脚本时,pdf文件在我的窗口中从未显示出来。你知道我哪里做错了吗?
我看到过这个话题 是否可以让QWebKit显示pdf文件?,但是那个答案对我没有用(在导入行中把PyQt改成Pyside后)。
我还看到过这个话题 使用QWebView显示PDF:加载后缺少刷新/重绘,那里的解决方法(在加载前使用定时器)对我有效。不过,我觉得用定时器来加载文件并不是解决问题的好办法。
而且,主要是我用来生成Ui_MainWindow
的代码是QtCreator自动生成的,我没有改动过,也不想自己改动(不想不使用QtCreator)。这只是一个简单的窗口表单,里面只有一个小部件QtWebKit.QWebView
,我想在里面加载一个文件。它应该能正常工作,而不需要奇怪的解决方法。为什么自动生成的代码不工作呢?我是不是用错了QtCreator?
1 个回答
1
你需要开启 QWebView
的插件功能:
self.webView = QtWebKit.QWebView(self.centralWidget)
self.webView.settings().setAttribute(QWebSettings.PluginsEnabled, True)
另外,试着在显示主窗口之后再设置 QWebView
的网址。
MW = MainWindow()
MW.show()
MW.ui.webView.setUrl(QtCore.QUrl("file:///C:/pdf_folder/test.pdf"))
我觉得绘图事件和你看不到PDF文件是有关系的。