开发者社区> 问答> 正文

如何在PyQt5的窗口中调整QWebEnginePage的大小?

有人可以告诉我如何调整此QWebEnginePage的大小。当我运行此文件时,它会打开一个具有完整浏览器的窗口,就像打开了网站一样,但是我想调整它的大小以在窗口中添加按钮和其他元素。

这是我的代码:

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, QtWebChannel, QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QSizeGrip, QGridLayout
from jinja2 import Template
#import D_scraper

class Form(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        # self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        # for making the window draggable
        self.oPos = self.pos()
        self.setFixedSize(1000, 650)

        testlw = QVBoxLayout()


        testlo = QGridLayout()
        testlo.addLayout(testlw, 0, 1)

        self.setLayout(testlo)
        self.setWindowTitle('test')
        self.setStyleSheet('background-color: rgb(255,255,0);')
        self.setStyleSheet('border-radius: 30px')

class Element(QtCore.QObject):
    def __init__(self, name, parent=None):
        super(Element, self).__init__(parent)
        self._name = name

    @property
    def name(self):
        return self._name

    def script(self):
        return ""

class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self, parent=None):
        super(WebEnginePage, self).__init__(parent)
        self.loadFinished.connect(self.onLoadFinished)
        self._objects = []
        self._scripts = []


    def add_object(self, obj):
        self._objects.append(obj)

    @QtCore.pyqtSlot(bool)
    def onLoadFinished(self, ok):
        print("Finished loading: ", ok)
        if ok:
            self.load_qwebchannel()
            self.add_objects()

    def load_qwebchannel(self):
        file = QtCore.QFile(":/qtwebchannel/qwebchannel.js")
        if file.open(QtCore.QIODevice.ReadOnly):
            content = file.readAll()
            file.close()
            self.runJavaScript(content.data().decode())
        if self.webChannel() is None:
            channel = QtWebChannel.QWebChannel(self)
            self.setWebChannel(channel)

    def add_objects(self):
        if self.webChannel() is not None:
            objects = {obj.name: obj for obj in self._objects}
            self.webChannel().registerObjects(objects)
            _script = """
            {% for obj in objects %}
            var {{obj}};
            {% endfor %}
            new QWebChannel(qt.webChannelTransport, function (channel) {
            {% for obj in objects %}
                {{obj}} = channel.objects.{{obj}};
            {% endfor %}
            }); 
            """
            self.runJavaScript(Template(_script).render(objects=objects.keys()))
            for obj in self._objects:
                if isinstance(obj, Element):
                    self.runJavaScript(obj.script())


class Helper(Element):
    classClicked = QtCore.pyqtSignal(str)

    def script(self):
        js = """
        document.addEventListener('click', function(e) {
            e = e || window.event;
            var target = e.target || e.srcElement;
            e.preventDefault()
            {{name}}.objectClicked(target.className);
        }, false);"""
        return Template(js).render(name=self.name)

    @QtCore.pyqtSlot(str)
    def objectClicked(self, className):
        if className:
            self.classClicked.emit(className)

def on_clicked(name):
    on_clicked.xcv = name
    print(on_clicked.xcv)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    window = Form()
    classname_helper = Helper("classname_helper")
    classname_helper.classClicked.connect(on_clicked)
    view = QtWebEngineWidgets.QWebEngineView()
    page = WebEnginePage()
    page.add_object(classname_helper)
    view.setPage(page)
    view.load(QtCore.QUrl("https://www.flipkart.com/search?q=mobiles&as=on&as-show=on&otracker=AS_Query_TrendingAutoSuggest_1_0_na_na_na&otracker1=AS_Query_TrendingAutoSuggest_1_0_na_na_na&as-pos=1&as-type=TRENDING&suggestionId=mobiles&requestId=4720716a-cf2f-4822-9036-c66b9542d2d6"))
    view.show()
    sys.exit(app.exec_())

我是QT Framework的新手,所以遇到了这个问题。您可以在窗口内添加一个按钮以及调整大小的浏览器作为示例,以便我理解。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 22:49:51 2520 0
1 条回答
写回答
取消 提交回答
  • 您需要创建一个“容器”窗口小部件,然后将视图嵌入其中。

    您已经到了一半,因为您已经创建了一个小部件,只需要将布局正确设置为该小部件,然后向其添加子级小部件即可。

    class Form(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(Form, self).__init__(parent)
            self.setWindowTitle('test')
            self.setMinimumSize(320, 240)
            self.resize(640, 480)
    
            testlo = QGridLayout()
            self.setLayout(testlo)
    
            self.testButton = QtWidgets.QPushButton('test button')
            testlo.addWidget(self.testButton)
    
            self.testLabel = QtWidgets.QLabel('test label')
            # add a label in the first row of the grid, second column
            testlo.addWidget(self.testLabel, 0, 1)
    
            self.view = QtWebEngineWidgets.QWebEngineView()
            # add the view to the second row, but let it occupy two columns
            testlo.addWidget(self.view, 1, 0, 1, 2)
    
            classname_helper = Helper("classname_helper")
            classname_helper.classClicked.connect(on_clicked)
            self.page = WebEnginePage()
            self.page.add_object(classname_helper)
            self.view.setPage(self.page)
            self.view.load(QtCore.QUrl("https://www.flipkart.com/search?q=mobiles&as=on&as-show=on&otracker=AS_Query_TrendingAutoSuggest_1_0_na_na_na&otracker1=AS_Query_TrendingAutoSuggest_1_0_na_na_na&as-pos=1&as-type=TRENDING&suggestionId=mobiles&requestId=4720716a-cf2f-4822-9036-c66b9542d2d6"))
    
            # if you call setStyleSheet() multiple times, it always overwrites the
            # previously set stylesheet, just use it once with the full contents
            self.setStyleSheet('''
                background-color: rgb(255,255,0);
                border-radius: 30px;
            ''')
    
    # ...
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        window = Form()
        window.show()
        sys.exit(app.exec_())
    

    回答来源:stackoverflow

    2020-03-24 22:50:00
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载