Skip to content
This repository was archived by the owner on Sep 19, 2025. It is now read-only.

Commit 44172c6

Browse files
authored
Update navegador.py
1 parent 0439815 commit 44172c6

File tree

1 file changed

+22
-29
lines changed

1 file changed

+22
-29
lines changed

navegador.py

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -31,32 +31,32 @@ def __init__(self):
3131
# Botões da barra de navegação
3232
back_btn = QAction("⬅️ Voltar", self)
3333
back_btn.setStatusTip("Voltar para a página anterior")
34-
back_btn.triggered.connect(lambda: self.current_browser().back()) # Conecta a uma lambda para chamar no clique
34+
back_btn.triggered.connect(lambda: self.current_browser().back())
3535
self.toolbar.addAction(back_btn)
3636

3737
forward_btn = QAction("➡️ Avançar", self)
3838
forward_btn.setStatusTip("Avançar para a próxima página")
39-
forward_btn.triggered.connect(lambda: self.current_browser().forward()) # Conecta a uma lambda
39+
forward_btn.triggered.connect(lambda: self.current_browser().forward())
4040
self.toolbar.addAction(forward_btn)
4141

4242
reload_btn = QAction("🔄 Recarregar", self)
4343
reload_btn.setStatusTip("Recarregar a página atual")
44-
reload_btn.triggered.connect(lambda: self.current_browser().reload()) # Conecta a uma lambda
44+
reload_btn.triggered.connect(lambda: self.current_browser().reload())
4545
self.toolbar.addAction(reload_btn)
4646

4747
home_btn = QAction("🏠 Início", self)
4848
home_btn.setStatusTip("Ir para a página inicial")
49-
home_btn.triggered.connect(self.navigate_home) # Essa já estava OK
49+
home_btn.triggered.connect(self.navigate_home)
5050
self.toolbar.addAction(home_btn)
5151

5252
self.url_bar = QLineEdit()
5353
self.url_bar.returnPressed.connect(self.navigate_to_url)
5454
self.toolbar.addWidget(self.url_bar)
5555

56-
# Botão para adicionar nova guia
56+
# Botão para adicionar nova guia - AGORA USANDO LAMBDA PARA GARANTIR NENHUM ARGUMENTO
5757
new_tab_btn = QAction("➕ Nova Guia", self)
5858
new_tab_btn.setStatusTip("Abrir uma nova guia")
59-
new_tab_btn.triggered.connect(self.add_new_tab)
59+
new_tab_btn.triggered.connect(lambda: self.add_new_tab()) # <--- AQUI ESTÁ A MUDANÇA PRINCIPAL
6060
self.toolbar.addAction(new_tab_btn)
6161

6262

@@ -70,18 +70,19 @@ def __init__(self):
7070

7171
def current_browser(self):
7272
"""Retorna a instância do navegador da guia atual."""
73-
# Garante que sempre haja um widget antes de tentar acessá-lo
7473
if self.tabs.count() > 0:
7574
return self.tabs.currentWidget()
76-
return None # Retorna None se não houver abas (embora sempre teremos uma)
75+
return None
7776

7877
def add_new_tab(self, qurl=None, label="Nova Guia"):
7978
"""Adiciona uma nova guia ao navegador."""
80-
if qurl is None:
79+
# Se qurl é None, ele significa que a chamada veio sem argumento (e deve usar o padrão)
80+
# Se vier um bool (True/False), isso é um sinal indesejado, então redefinimos para o padrão
81+
if qurl is None or isinstance(qurl, bool):
8182
qurl = QUrl("https://www.google.com") # Padrão para nova aba
8283

8384
browser = BrowserTab()
84-
browser.setUrl(qurl)
85+
browser.setUrl(qurl) # Agora qurl será sempre um QUrl
8586

8687
i = self.tabs.addTab(browser, label)
8788
self.tabs.setCurrentIndex(i)
@@ -98,15 +99,15 @@ def add_new_tab(self, qurl=None, label="Nova Guia"):
9899
def tab_open_doubleclick(self, index):
99100
"""Abre uma nova guia ao dar clique duplo na barra de abas."""
100101
if index == -1: # Clicou em uma área vazia
101-
self.add_new_tab()
102+
self.add_new_tab() # Chama sem argumentos explícitos
102103

103104
def current_tab_changed(self, index):
104105
"""Atualiza a barra de URL quando a guia ativa muda."""
105106
browser = self.current_browser()
106107
if browser:
107108
qurl = browser.url()
108109
self.update_urlbar(qurl, browser)
109-
self.update_buttons_state() # Garante que os botões refletem a guia atual
110+
self.update_buttons_state()
110111

111112
def navigate_home(self):
112113
"""Volta para a página inicial."""
@@ -121,60 +122,52 @@ def navigate_to_url(self):
121122
"""
122123
url = self.url_bar.text()
123124
browser = self.current_browser()
124-
if not browser: # Se não houver navegador ativo, não faz nada
125+
if not browser:
125126
return
126127

127-
# 1. Adiciona https:// se não houver protocolo
128128
if not url.startswith("http://") and not url.startswith("https://"):
129-
# Verifica se parece um domínio (contém pelo menos um ponto)
130-
if "." in url and not " " in url: # Garante que não é uma frase com espaços
131-
url = "https://" + url # Tenta HTTPS por padrão
129+
if "." in url and not " " in url:
130+
url = "https://" + url
132131
else:
133-
# 2. Se não parecer uma URL, faz uma pesquisa no Google
134132
search_query = QUrl.toPercentEncoding(url)
135133
url = f"https://www.google.com/search?q={search_query}"
136134

137135
browser.setUrl(QUrl(url))
138-
self.update_buttons_state() # Atualiza o estado dos botões após a navegação
136+
self.update_buttons_state()
139137

140138
def update_urlbar(self, q, browser=None):
141139
"""Atualiza a barra de URL com a URL da guia atual."""
142-
# Apenas atualiza se o navegador passado for o navegador atual ou se não houver um navegador específico
143140
if browser is None or browser == self.current_browser():
144141
self.url_bar.setText(q.toString())
145-
self.url_bar.setCursorPosition(0) # Volta o cursor para o início
142+
self.url_bar.setCursorPosition(0)
146143

147144
def update_buttons_state(self):
148145
"""Atualiza o estado (habilitado/desabilitado) dos botões de navegação."""
149146
browser = self.current_browser()
150147
if browser:
151-
# Acessa o histórico para verificar se pode voltar/avançar
152148
history = browser.history()
153149
can_go_back = history.canGoBack()
154150
can_go_forward = history.canGoForward()
155151
else:
156-
# Se não houver navegador, desabilita tudo
157152
can_go_back = False
158153
can_go_forward = False
159154

160155
for action in self.toolbar.actions():
161156
if action.text() == "⬅️ Voltar":
162-
# Habilita "Voltar" se houver um navegador, puder voltar e não estiver na página inicial
163157
action.setEnabled(browser is not None and can_go_back and browser.url() != QUrl("https://www.google.com"))
164158
elif action.text() == "➡️ Avançar":
165159
action.setEnabled(browser is not None and can_go_forward)
166160
elif action.text() == "🔄 Recarregar":
167-
action.setEnabled(browser is not None) # Recarregar sempre que houver um navegador
161+
action.setEnabled(browser is not None)
168162
elif action.text() == "🏠 Início":
169-
action.setEnabled(browser is not None) # Home sempre que houver um navegador
163+
action.setEnabled(browser is not None)
170164
elif action.text() == "➕ Nova Guia":
171-
action.setEnabled(True) # Nova guia sempre habilitada
165+
action.setEnabled(True)
172166

173167

174-
# Função principal para rodar o aplicativo
175168
if __name__ == "__main__":
176169
app = QApplication(sys.argv)
177-
QApplication.setApplicationName("Navegador Py-Tech") # Define o nome da aplicação para o sistema
170+
QApplication.setApplicationName("Navegador Py-Tech")
178171
navegador = MiniNavegador()
179172
navegador.show()
180173
sys.exit(app.exec_())

0 commit comments

Comments
 (0)