问题描述
我在一个项目上工作:程序下载但我在使用 while 循环时遇到问题,用于检查与 internet 的连接,如果 true 不 settext('') to lable 和 if flase settext('anytext') to lable
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
连接检查方法
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('')
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('')
构造者
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
主代码
def main(): app = qapplication(sys.argv) window = mainapp() window.checkinternetconnection() window.show() app.exec() if __name__=='__main__': main()
推荐答案
qthread不要太复杂,使用线程库:
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()
另一方面,由于您使用的是线程,因此不应从另一个线程更新 gui,为此您可以使用 qmetaobject::invokemethod:
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()