Search code examples
pythonpyqtqthread

How to let a Qthread alter a variable from the main class?


I am trying to figure out how pass variables between my Main class and a QThread. The idea is the QThread would be able to alter and return the variable. Specifically, I want to do this with a smtplib session. I understand how to update UI elements from a QThread using signals and slots, but what about just giving me the altered variable without displaying it in a label or similar? Especially since the variable is not a simple data type like int or str.

I am a beginner to both python and pyqt, and am thoroughly confused by QMutex and other things I'm reading about. I'm not opposed to researching on my own if you can point me in the right direction that someone at my level could understand.

Here is some code that I think shows what I am trying to do:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import smtplib

import mainwindow


class Main(QMainWindow, mainwindow.Ui_MainWindow):

    def __init__(self, parent=None):
        super(Main, self).__init__(parent)
        self.setupUi(self)

        self.start_smtp_button.clicked.connect(self.start_smtp)

    def start_smtp(self):

        smtp = self.smtp_lineEdit.text()
        port = self.port_lineEdit.text()

        self.a_thread = Thread(smtp, port)
        self.a_thread.start()

    def login(self):

        #  if I had access to the 's' from my thread, I could do other stuff with it, right?


class Thread(QThread):   

    def __init__(self, smtp, port, parent=None):
        super(Thread, self).__init__(parent)

        self.smtp = smtp
        self.port = port

    def run(self):

        s = smtplib.SMTP(host=self.smtp, port=int(self.port))


def main():

    app = QApplication(sys.argv)
    form = Main()
    form.show()
    app.exec_()


if __name__ == '__main__':
    main()

Solution

  • So it was suggested to me by a professional developer friend that I should make my smtp session a global variable. I had read not to do that generally, but considering the source of the advice on this one, I'm going with it. Thanks for all the help and I'll continue to monitor this question is anyone has other ideas.