gpt4 book ai didi

python - 如何在 QWebKit 浏览器中保持当前 URL 更新

转载 作者:行者123 更新时间:2023-12-01 07:17:22 25 4
gpt4 key购买 nike

我正在使用 PyQt5 WebKit 制作一个带有搜索框的非常简单的浏览器。这是我正在使用的代码:

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QMainWindow, QGridLayout)
from PyQt5.QtWebKitWidgets import QWebView


class App(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)

centralWidget = QWidget()
self.setCentralWidget(centralWidget)

self.searchbox = QLineEdit("", self)
self.go = QPushButton('Go', self)
self.go.clicked.connect(self.gourl)
self.webview = Browser()

self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.webview, 0, 0, 1, 4)
self.grid.addWidget(self.searchbox, 1, 0)
self.grid.addWidget(self.go, 1, 1)

def gourl(self):
url = self.searchbox.text()
self.webview.load(QUrl(url))


class Browser(QWebView): #(QWebView):
windowList = []
def createWindow(self, QWebEnginePage_WebWindowType):
App.setCentralWidget(Browser())
#new_window.show()
self.windowList.append(App())
return Browser()

if __name__ == "__main__":
app = QApplication(sys.argv)
box = App()
box.setWindowTitle('Browser')
box.resize(600, 500)
box.show()
sys.exit(app.exec_())

我想用用户当前所在的 URL 来更新框中的 URL。我不知道如何解决这个问题,任何帮助将不胜感激。

最佳答案

下面是您的示例的重写,它应该可以满足您的要求。

Browser 类已得到修复,以便在请求新窗口时创建 App 的新实例。您可以通过右键单击链接并选择在新窗口中打开来测试这一点。只要新的网址发生变化,搜索框就会自动更新。

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QMainWindow, QGridLayout)
from PyQt5.QtWebKitWidgets import QWebView


class App(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)

centralWidget = QWidget()
self.setCentralWidget(centralWidget)

self.searchbox = QLineEdit("", self)
self.go = QPushButton('Go', self)
self.go.clicked.connect(self.gourl)
self.webview = Browser()
self.webview.urlChanged.connect(self.handleUrlChanged)

self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.webview, 0, 0, 1, 4)
self.grid.addWidget(self.searchbox, 1, 0)
self.grid.addWidget(self.go, 1, 1)

def gourl(self):
url = self.searchbox.text()
self.webview.load(QUrl(url))

def handleUrlChanged(self, url):
self.searchbox.setText(url.toString())


class Browser(QWebView):
windowList = []

def createWindow(self, wintype):
window = App()
self.windowList.append(window)
window.show()
return window.webview

def closeEvent(self, event):
self.windowList.remove(self)
super().closeEvent(event)


if __name__ == "__main__":

app = QApplication(sys.argv)
box = App()
box.setWindowTitle('Browser')
box.resize(600, 500)
box.show()
sys.exit(app.exec_())

关于python - 如何在 QWebKit 浏览器中保持当前 URL 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57890665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com