如何使用PyQt5循环运行

时间:2019-01-15 22:21:24

标签: python multithreading user-interface pyqt5

我在一个项目上工作:程序下载,但是用while循环检查与互联网的连接是否存在问题,如果为true,则setText('')不会变为lable,而Flase setText('anyText')变为able

检查连接的方法

    def checkInternetConnection(self,host="8.8.8.8", port=53, timeout=3):

    while self.conection==False:
        try:
            socket.setdefaulttimeout(timeout)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
            self.conection = True
            return self.conection

        except Exception as e:
                print(e)
                self.label_9.setText('Please Check Internect Connection')
                self.conection = False
                return self.conection
    self.finished.emit()

我对QThread感到厌倦。请我怎么做:)?当应用程序运行时,如果连接丢失= False setText('check internet'),并且当连接变为true时,setText('')

构造器

From_Class,_=loadUiType(os.path.join(os.path.dirname(__file__),'designe.ui'))
class mainApp(QMainWindow,From_Class):
    finished = pyqtSignal()
    def __init__(self,parent=None):
        super(mainApp, self).__init__(parent)
        QMainWindow.__init__(self)
        super().setupUi(self)
        self.handleGui()
        self.handleButton()
        self.setWindowIcon(QIcon('mainIcon.png'))
        self.menuBarW()
        self.conection = False

MainCode

def main():
    app = QApplication(sys.argv)
    window = mainApp()
    window.checkInternetConnection()
    window.show()
    app.exec()

if __name__=='__main__':
    main()

1 个答案:

答案 0 :(得分:0)

不要对QThread感到复杂,请使用线程库:

def main():
    app = QtWidgets.QApplication(sys.argv)
    window = mainApp()
    threading.Thread(target=window.checkInternetConnection, daemon=True).start()
    window.show()
    app.exec()

另一方面,由于您正在使用线程,因此不应从其他线程更新GUI,为此您可以使用QMetaObject::invokeMethod

def checkInternetConnection(self,host="8.8.8.8", port=53, timeout=3):
    while True:
        try:
            socket.setdefaulttimeout(timeout)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
            self.conection = True
        except Exception as e:
            self.conection = False
            print(e)
        msg = "" if self.conection else 'Please Check Internect Connection'
        print("msg", msg)
        QtCore.QMetaObject.invokeMethod(self.label_9, "setText",
            QtCore.Qt.QueuedConnection,  
            QtCore.Q_ARG(str, msg))
    self.finished.emit()