使用 QtNetwork 和 PyQt5 检查互联网连接

Checking internet connectivity using QtNetwork and PyQt5

我正在尝试使用 QtNetwork 以困难的方式检查网络连接,但不知道如何正确地进行。这是我正在处理的代码,似乎 finishederror 信号都没有被调用。我在这里缺少什么?

import sys
from PyQt5 import QtCore, QtNetwork, QtWidgets


class CheckConnectivity:
    def __init__(self):
        url = QtCore.QUrl("https://www.google.com/")
        req = QtNetwork.QNetworkRequest(url)
        net_manager = QtNetwork.QNetworkAccessManager()
        self.res = net_manager.get(req)
        self.res.finished.connect(self.processRes)
        self.res.error.connect(self.processErr)
        self.msg = QtWidgets.QMessageBox()

    def processRes(self):
        if self.res.bytesAvailable():
            self.msg.information(self, "Info", "You are connected to the Internet.")
        else:
            self.msg.critical(self, "Info", "You are not connected to the Internet.")
        self.msg.show()
        self.res.close()

    def processErr(self, *args):
        print(*args)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    ic = CheckConnectivity()
    sys.exit(app.exec_())

问题是因为net_manager被移除了,记住一个变量只存在于创建它的上下文中,在你的例子中net_manager是一个局部变量,当__init__ 方法结束。

class CheckConnectivity(QtCore.QObject):
    def __init__(self, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        url = QtCore.QUrl("https://www.google.com/")
        req = QtNetwork.QNetworkRequest(url)
        self.net_manager = QtNetwork.QNetworkAccessManager()
        self.res = self.net_manager.get(req)
        self.res.finished.connect(self.processRes)
        self.res.error.connect(self.processErr)
        self.msg = QtWidgets.QMessageBox()

    @QtCore.pyqtSlot()
    def processRes(self):
        if self.res.bytesAvailable():
            self.msg.information(None, "Info", "You are connected to the Internet.")
        self.res.deleteLater()

    @QtCore.pyqtSlot(QtNetwork.QNetworkReply.NetworkError)
    def processErr(self, code):
        self.msg.critical(None, "Info", "You are not connected to the Internet.")
        print(code)

建议使用 pyqtSlot() 装饰器,因为它的使用有助于应用程序更快一点并消耗更少的内存,但为此 class 必须继承自 QObject