How to set the size of browser using QtWebKit

2020-06-06 02:08发布

Recently I use PyQt4 to crawl some web pages. I want to set different size of the browser which is generated by QWebView().show(). I tried to use the following code snippet to set the size:

self.qsize = QWebPage().viewportSize()
self.qsize.setHeight(3000)
self.qsize.setWidth(1000)
print self.qsize.height()
print self.qsize.width()

But the browser displayed is always the same size.

Please give me some tips on how to set the size of the browser displayed by QWebView. Thanks in advance.

1条回答
一夜七次
2楼-- · 2020-06-06 02:18

I tested this, the window resizes itself after loadFinished is emitted:

import sys 
from PySide.QtCore import QUrl, QSize
from PySide.QtGui import QApplication, QMainWindow, QWidget
from PySide.QtWebKit import QWebView


class Browser(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(300, 300)
        self.web_view = QWebView()
        self.setCentralWidget(self.web_view)

        self.web_view.loadFinished.connect(self._load_finished)

    def _load_finished(self):
        frame = self.web_view.page().mainFrame()
        self.web_view.page().setViewportSize(frame.contentsSize())
        self.resize(frame.contentsSize())
        html_data = frame.toHtml()


if __name__ == '__main__': 
    app = QApplication(sys.argv) 
    browser = Browser() 
    r = QUrl("http://www.yahoo.com")
    browser.web_view.load(r)
    browser.show()
    app.exec_()
查看更多
登录 后发表回答