Display PDF file with QWebView

你离开我真会死。 提交于 2019-12-22 09:26:56

问题


I would like to display a window with a QwebView widget in Pyside. For this I use some code generated by 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_())

I am sure to have a pdf file in the specified path, but when I run my script, the pdf file is never displayed in my window. Do you know what I am doing wrong ?

I saw this topic Is it possible to get QWebKit to display pdf files?, but the answer don't work for me (after changing PyQt to Pyside in the import lines).

I also saw this topic PDF with QWebView: missing refresh/repaint after loading, the workaround (using a timer before loading) work for me. however I don't think that using a timer to load a file is a good way to solve the problem.

And, mainly, the code that I used for Ui_MainWindow is generated with QtCreator, I didn't change it and I don't want to change it by myself (without using QtCreator). It is just a simple form for a window with only one widget QtWebKit.QWebView in which I want to load a file. It should work without weird workaround. Why the code automatically generated don't work ? Am I using QtCreator in a wrong way ?


回答1:


You have to enable QWebView's plugins:

self.webView = QtWebKit.QWebView(self.centralWidget)
self.webView.settings().setAttribute(QWebSettings.PluginsEnabled, True)

also try to set the QWebView URL after showing the main window.

MW = MainWindow()
MW.show()
MW.ui.webView.setUrl(QtCore.QUrl("file:///C:/pdf_folder/test.pdf"))

I think the paint events has to do with the fact you don't see the pdf file.



来源:https://stackoverflow.com/questions/24613347/display-pdf-file-with-qwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!