Updating variable values when running a thread using QThread in PyQt4

2024/10/13 1:24:37

So problem occurred when I tried using Threading in my code. What I want to do is passing default values to the def __init__ and then calling the thread with its instance with updated values but somehow I cannot get the updated values.

Below is my initial code: main.py

from PyQt4 import QtGui
import sys
import GUI # GUI app by using PYQT4
from PyQt4.QtCore import QThread
#import Photosclass PyMain(QtGui.QWidget, GUI.Ui_Pycloud):def __init__(self):super(self.__class__, self).__init__()self.setupUi(self)self.password.setEchoMode(QtGui.QLineEdit.Password)"""Picking up data from GUI.py file where initially,it is set to 'Username' and 'Password' respectively.and initialising `GetThread` class"""self.get_thread = GetThread(str(self.username.text()), str(self.password.text()))"""This is what I was initially using.I have tried, only passing the instance and calling get_thread.start() inside __init__ fn but even if i don't click `commandLinkButton` it is somehow called automatically.I know it is not the right approach"""self.commandLinkButton.clicked.connect(self.get_thread.start)class GetThread(QThread):def __init__(self, username, password):QThread.__init__(self)self.username = usernameself.password = passworddef __del__(self):self.wait()def authentication(self):print self.username, self.password# user = Photos.PyPhotos(self.username, self.password)# user.authentication(user)def run(self):self.authentication()def main():app = QtGui.QApplication(sys.argv)form = PyMain()form.show()app.exec_()if __name__ == '__main__':main()

Below is what I tried:

...........................
...........................
...........................class PyMain(QtGui.QWidget, GUI.Ui_Pycloud):def __init__(self):super(self.__class__, self).__init__()self.setupUi(self)self.password.setEchoMode(QtGui.QLineEdit.Password)self.commandLinkButton.clicked.connect(GetThread(str(self.username.text()), str(self.password.text())).__init__)class GetThread(QThread):def __init__(self, username, password):QThread.__init__(self)self.username = usernameself.password = passwordself.start()
...........................
...........................
...........................

Result: Username Password

Which is shown the moment I run my main.py file, whereas I should get this only and only if I press commandLinkButton and should update variables if I update them on my GUI which is not happening.

EDIT: Below is what I tried again, it is showing me the correct output if I update them on GUI but threading is not working in this case:

..............
..............
..............
class PyMain(QtGui.QWidget, GUI.Ui_Pycloud):def __init__(self):super(self.__class__, self).__init__()self.setupUi(self)self.password.setEchoMode(QtGui.QLineEdit.Password)self.commandLinkButton.clicked.connect(self.populate)def populate(self):get_thread = GetThread(str(self.username.text()), str(self.password.text()))get_thread.start()class GetThread(QThread):def __init__(self, username, password):QThread.__init__(self)self.username = usernameself.password = passworddef __del__(self):self.wait()def authentication(self):print self.username, self.passworduser = Photos.PyPhotos(self.username, self.password)user.authentication(user)def run(self):self.authentication()
......................
......................
......................

So anyone can please tell me how to approach this?

Answer

You need to use a custom signal to send the authentication result back the main thread. But note that you must not perform any gui operations of any kind outside the main thread. So, for example, the worker thread cannot show an authentication dialog or attempt to directly update widgets. All it can do is execute a lengthy non-gui process and send the result back to the main thread when it's finished.

The basic structure of the code should look like this:

class PyMain(QtGui.QWidget, GUI.Ui_Pycloud):def __init__(self):super(self.__class__, self).__init__()self.setupUi(self)self.password.setEchoMode(QtGui.QLineEdit.Password)self.commandLinkButton.clicked.connect(self.populate)def populate(self):self.thread = GetThread(self.username.text(), self.password.text())self.thread.authResult.connect(self.handleAuthResult)self.thread.start()def handleAuthResult(self, result):# do something with result...class GetThread(QThread):authResult = QtCore.pyqtSignal(object)def __init__(self, username, password):QThread.__init__(self)self.username = usernameself.password = passworddef authentication(self):result = do_authentication()self.authResult.emit(result)def run(self):self.authentication()
https://en.xdnf.cn/q/118136.html

Related Q&A

Show terminal status in a Tkinter widget

I am using python2.7.10 on MacOs Sierra and have created a rsync over ssh connection with my raspberrypi. The Idea is to synchronize my local folder with my remote folder on the raspberrypi. My functio…

Python Convert HTML into JSON using Soup

These are the rulesThe HTML tags will start with any of the following <p>, <ol> or <ul> The content of the HTML when any of step 1 tags is found will contain only the following tags: …

I/O Error while saving Excel file - Python

Im using python to open an existing excel file and do some formatting and save and close the file. My code is working good when the file size is small but when excel size is big (apprx. 40MB) Im gettin…

How to stop the python turtle from drawing

Can anyone tell me why this code always has a line on the screen and also how to stop it?Slight problem with this is that every time this happens, I always get a line on my canvas no matter what I try…

Replace values in a string

So the challenge was to replace a specific word in a sentence with asterisks with equivalent length to that word - 3 letters 3 asterisks etc.Section One does not work, but Section Two does - can anyon…

Select n data points from plot

I want to select points by clicking om them in a plot and store the point in an array. I want to stop selecting points after n selections, by for example pressing a key. How can I do this? This is wha…

Python azure uploaded file content type changed to application/octet-stream

I am using python Azure sdk. When the file uploaded its content type changed to application/octet-stream. I want to set its default content type like image/png for PNG image.I am using following method…

the dumps method of itsdangerous throws a TypeError

I am following the guide of 『Flask Web Development』. I want to use itsdangerous to generate a token, but some problems occured. Here is my code:def generate_confirmation_token(self, expiration=3600):…

SP 500 List python script crashes

So I have been following a youtube tutorial on Python finance and since Yahoo has now closed its doors to the financial market, it has caused a few dwelling problems. I run this codeimport bs4 as bs im…

sleekxmpp threaded authentication

so... I have a simple chat client like so:class ChatClient(sleekxmpp.ClientXMPP):def __init__(self, jid, password, server):sleekxmpp.ClientXMPP.__init__(self, jid, password, ssl=True)self.add_event_han…