I work on one Project : Program download but I have a problem with while loop for check the connection with the internet and if true doesn't setText('') to lable and if Flase setText('anyText') to lable
Method for check the connection
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()
I have tired with QThread . Please How I can do it :) ? And when app is running if connection is lost=False setText('check internet') and when the connection become true setText('')
CONSTRUCTOR
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()
Do not get complicated with QThread, use the threading library:
def main():
app = QtWidgets.QApplication(sys.argv)
window = mainApp()
threading.Thread(target=window.checkInternetConnection, daemon=True).start()
window.show()
app.exec()
On the other hand, since you are using a thread, you should not update the GUI from another thread, for this you can use 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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.