# Importa tutte le classi per costruire GUI con Qt from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtWebEngineWidgets import * #from PyQt5.QtWebKitWidgets import * class WebBrowser: def __init__(self): '''Crea un'applicazione Qt e una finestra''' # verifica se l'applicazione è già esistente self.app = QApplication.instance() # o ne crea una nuova if not self.app: self.app = QApplication([]) self.window = QWidget() self.window.resize(800, 600) self.window.setWindowTitle('Fondamenti di Programmazione') # Crea il layout per la finestra layout = QVBoxLayout() # Crea il layout per la toolbar tlayout = QHBoxLayout() # Crea la navigation bar e i bottoni di navigazione self.text_bar = QLineEdit('... URL ...') button_back = QPushButton('<') button_forward = QPushButton('>') # Aggiunge i widgets alla toolbar tlayout.addWidget(button_back) tlayout.addWidget(button_forward) tlayout.addWidget(self.text_bar) # Aggiunge la toolbar alla finestra layout.addLayout(tlayout) # Crea un widget per visualizzare pagine web #self.web_view = QWebView() #QWebEngineView() self.web_view = QWebEngineView() # lo aggiunge al layout della finestra layout.addWidget(self.web_view) # Imposta il layout della finestra self.window.setLayout(layout) # Imposta la callback della navigation bar self.text_bar.returnPressed.connect(self.load_page) # Imposta la callback della web_view self.web_view.urlChanged.connect(self.set_url) # Imposta le callback dei due bottoni button_back.clicked.connect(self.web_view.back) button_forward.clicked.connect(self.web_view.forward) def run(self): '''Rende la finestra visibile e lancia l'applicazione''' self.window.show() self.app.exec_() # Definisce la callback del bottone def exit_callback(self): print('Exit clicked') self.window.close() self.app.quit() # La callback per il nuovo url nella navigation bar def set_url(self): self.text_bar.setText(self.web_view.url().toString()) # La callback per caricare una pagina def load_page(self): if self.text_bar.text() == self.web_view.url().toString(): return text = self.text_bar.text() # se vogliamo aprire un file if 'file://' in text: pass # se non sembra un url lo cerchiamo su google elif ' ' in text or '.' not in text: text = 'http://google.com/search?q=' + text # altrimenti se manca il prefisso lo aggiungiamo elif '://' not in text: text = 'http://'+text # e finalmente apriamo l'URL self.web_view.setUrl(QUrl(text)) if __name__ == '__main__': app = WebBrowser() app.run()