thread4/navegadores/BrowserApp.py

66 lines
2.2 KiB
Python

import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QVBoxLayout, QWidget, QLineEdit, QAction, QToolBar
from PyQt5.QtWebEngineWidgets import QWebEngineView
class BrowserTab(QWebEngineView):
def __init__(self, url="https://google.com"):
super().__init__()
self.load(QUrl.fromUserInput(url)) # Convertir URL de str a QUrl
class BrowserApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Navegador Web con PyQt5")
self.resize(1024, 768)
# Barra de herramientas para la URL
self.toolbar = QToolBar()
self.addToolBar(self.toolbar)
# Campo de entrada para la URL
self.url_bar = QLineEdit()
self.url_bar.returnPressed.connect(self.navigate_to_url)
self.toolbar.addWidget(self.url_bar)
# Botón de nueva pestaña
new_tab_action = QAction("Nueva pestaña", self)
new_tab_action.triggered.connect(self.add_new_tab)
self.toolbar.addAction(new_tab_action)
# Contenedor de pestañas
self.tabs = QTabWidget()
self.tabs.setDocumentMode(True)
self.tabs.tabCloseRequested.connect(self.close_current_tab)
self.setCentralWidget(self.tabs)
# Añadir una primera pestaña
self.add_new_tab("https://google.com")
def add_new_tab(self, url="https://google.com"):
new_tab = BrowserTab(url)
i = self.tabs.addTab(new_tab, "Nueva Pestaña")
self.tabs.setCurrentIndex(i)
new_tab.urlChanged.connect(self.update_url_bar)
self.url_bar.setText(url)
def close_current_tab(self, index):
if self.tabs.count() > 1:
self.tabs.removeTab(index)
def navigate_to_url(self):
url = self.url_bar.text()
if not url.startswith("http"):
url = "http://" + url
# Navegar usando QUrl
self.tabs.currentWidget().setUrl(QUrl.fromUserInput(url))
def update_url_bar(self, qurl):
self.url_bar.setText(qurl.toString())
if __name__ == "__main__":
app = QApplication(sys.argv)
browser = BrowserApp()
browser.show()
sys.exit(app.exec_())