from PySide2.QtCore import * from PySide2.QtWidgets import * from PySide2.QtWebEngineWidgets import * class TabWidget(QTabWidget): def __init__(self, *args, **kwargs): QTabWidget.__init__(self, *args, **kwargs) url = QUrl("https://www.163.com") view = HtmlView(self) view.load(url) ix = self.addTab(view, "加载中 ...") self.resize(800, 600) class HtmlView(QWebEngineView): def __init__(self, *args, **kwargs): QWebEngineView.__init__(self, *args, **kwargs) self.tab = self.parent() def createWindow(self, windowType): if windowType == QWebEnginePage.WebBrowserTab: webView = HtmlView(self.tab) ix = self.tab.addTab(webView, "加载中 ...") self.tab.setCurrentIndex(ix) return webView return QWebEngineView.createWindow(self, windowType) if __name__ == "__main__": import sys app = QApplication(sys.argv) main = TabWidget() main.show() sys.exit(app.exec_()),在这段代码中添加关闭网页的按钮和功能。
时间: 2024-04-27 10:19:36 浏览: 206
你可以在 `TabWidget` 类中添加一个按钮,并连接到一个槽函数来关闭当前的 `HtmlView`。以下是修改后的代码:
```python
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from PySide2.QtWebEngineWidgets import *
class TabWidget(QTabWidget):
def __init__(self, *args, **kwargs):
QTabWidget.__init__(self, *args, **kwargs)
url = QUrl("https://www.163.com")
view = HtmlView(self)
view.load(url)
ix = self.addTab(view, "加载中 ...")
self.resize(800, 600)
# 添加关闭按钮
closeButton = QPushButton("关闭网页", self)
closeButton.clicked.connect(self.closeCurrentTab)
self.setCornerWidget(closeButton)
# 关闭当前标签页
def closeCurrentTab(self):
ix = self.currentIndex()
if ix >= 0:
view = self.widget(ix)
self.removeTab(ix)
view.deleteLater()
class HtmlView(QWebEngineView):
def __init__(self, *args, **kwargs):
QWebEngineView.__init__(self, *args, **kwargs)
self.tab = self.parent()
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
webView = HtmlView(self.tab)
ix = self.tab.addTab(webView, "加载中 ...")
self.tab.setCurrentIndex(ix)
return webView
return QWebEngineView.createWindow(self, windowType)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = TabWidget()
main.show()
sys.exit(app.exec_())
```
在上面的代码中,我们添加了一个按钮 `closeButton`,并将其设置为窗口的角落部件,这样它就会出现在标签页的右上角。当用户点击按钮时,它会触发 `closeCurrentTab` 槽函数,该函数会关闭当前标签页,并删除对应的 `HtmlView` 对象。
阅读全文