import sys
from PyQt5.QtCore import *
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtGui import QGuiApplication as App
from PyQt5.QtGui import QPixmap, QWindow
from PyQt5 import QtNetwork, QtCore, QtWidgets
import urllib
from urllib.request import urlopen
import threading
import time
class WebApp(QMainWindow):
def __init__(self):
self.is_connected = None
self.is_msgshow = True
self.msg = QtWidgets.QMessageBox()
super().__init__()
self.title = "OZI"
self.t_internet = threading.Thread(target=self.is_internet)
self.t_internet.start()
self.t_refreshpage = threading.Thread(target=self.refresh_page)
self.t_refreshpage.start()
self.web = QWebEngineView()
self.web.window().setWindowTitle(self.title)
self.web.load(QUrl("http://www.google.com"))
self.web.showFullScreen()
def is_internet(self):
"""
Query internet using python
:return:
"""
while True:
time.sleep(5)
try:
urlopen("http://www.google.com", timeout=1)
self.is_connected = True
except urllib.error.URLError as Error:
print(Error)
self.is_connected = False
print(self.is_connected)
def refresh_page(self):
while True:
time.sleep(.1)
if self.is_connected == False:
time.sleep(5)
if self.is_connected == True:
self.web.page().action(QWebEnginePage.Reload).trigger()
else:
if self.is_msgshow == True:
print('testtt')
self.msg.information(None, 'INFO', 'PLEASE CHECK YOUR INTERNET CONNECTION!!!')
self.is_msgshow = False
self.msg.close()
else:
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = WebApp()
sys.exit(app.exec_())
[嗨,此代码使用Qt浏览器打开网站。如果互联网连接丢失,我想使用QMessageBox提供信息消息。但是,我无法通过
成功 if self.is_msgshow == True:
print('testtt')
这部分在失去互联网连接的情况下,我的代码打开了许多MessageBox。我猜我的错是控制self.is_msgshow标志。
if self.is_msgshow == True:
print('testtt')
self.msg.information(None, 'INFO', 'PLEASE CHECK YOUR INTERNET CONNECTION!!!')
self.is_msgshow = False
self.msg.close()
self.msg.information()
调用是同步。如果是这样,则只要它保持打开状态,
附加说明,一旦连接恢复,您可能希望将其重置为is_msgshow
就仍然是True
,因为一旦关闭对话框,便要对其进行更改。这是您的错误,好像发生了新的甚至没有新的对话框一样。修复非常简单-只需将self.is_msgshow = False
移至该代码块中要做的第一件事,就可以了。True
,否则下一次网络中断时您不会看到任何信息。EDIT:
刚刚检查过,是的,QMessageBox
是我所假定的同步的:QMessageBox类提供了一个对话框,用于通知用户或向用户询问问题并接收答案。 https://doc.qt.io/qtforpython/PySide2/QtWidgets/QMessageBox.htmlmodal