简体   繁体   中英

How to read text from a QlineEdit which belongs to a MainWindow class, and use it into a Qthread class using python and pyqt?

I'm new to python and pyqt and I'm working on an app and I encountered a problem. I'm building a QThread class which sends by mail a .csv file, yesterday a fellow member showed me how to send str signals to a QtextBrowser found in Main Window. Now i need to read 3 QlineEdit which contains server address, user name and password. But it seems I do'nt understand very well how to read a str from those and send it where I need it.

The 3 QlineEdit are called: server_line , user_line , pass_line and when I try to read them in Main Window using this self.server_line.displayText() works fine, but when I try to read them from class MailSender I get error QPixmap: It is not safe to use pixmaps outside the GUI thread . I know I have to use signals and slots but I don't know how to do it in this case.

Let me show you a short version of my code:

import sys,os,time
import psutil,threading
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email import Encoders
import email.utils
from PyQt4 import QtGui, uic ,QtSql,QtCore
from PyQt4.QtCore import QThread, SIGNAL
from PyQt4.QtGui import *
from uuid import getnode as get_mac
import base64
from reportlab.pdfgen import canvas
import StringIO
from reportlab.lib.pagesizes import landscape
from reportlab.lib.pagesizes import letter
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.lib.units import inch
import icons

class MailSender(QtCore.QThread):
    newMessage = QtCore.pyqtSignal(str)
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

    def __del__(self):
        self.wait()

    def serverVal(self,val):
        self.server = val

    def clasa_MyWindow(self):
        self.clasa = MyWindow()


    def mail_send(self):
        #server = smtp mail server address and port
        #user = mail user
        #pass1 = mail password
        try:
            msg = MIMEMultipart('Inchideri .')
            msg['Subject'] = 'Inchideri '
            msg['From'] = (str(user + '@mail.ro'))
            msg['To'] = (str(destinatar))
            # -------------------------------------------------------
            mail_file = MIMEBase('application', 'csv')
            mail_file.set_payload(open("Raport.csv", 'rb').read())
            mail_file.add_header('Content-Disposition', 'attachment', filename="Raport.csv")
            Encoders.encode_base64(mail_file)
            msg.attach(mail_file)
            # ------------------------------------------------------
            conn = SMTP(str(server))
            conn.set_debuglevel(False)
            conn.login(str(user), str(pass1))
            try:
                conn.sendmail(str(user + '@mail.ro'), str(destinatar), msg.as_string())
                self.newMessage.emit("Sending Mail.....")
            finally:
                conn.quit()
                self.newMessage.emit("Mail Send OK")
        except Exception, exc:
            self.newMessage.emit("mail failed; %s" % str(exc))  # give a error message

    def run(self):
        self.mail_send()

class MyWindow(QtGui.QMainWindow):
    server1 = QtCore.pyqtSignal(str)
    def __init__(self,parent=None):
        QtGui.QMainWindow.__init__(self, parent=parent)
        file_path = os.path.abspath("im-manager.ui")
        uic.loadUi(file_path, self)
        self.mail_btn.pressed.connect(self.run_mail_class)
        .
        .
        .
        self.myThread1 = MailSender()
        self.myThread1.newMessage.connect(self.statusText_updater)

     def run_mail_class(self):
        self.myThread1.start()

    def statusText_updater(self,text):
        time_print = time.strftime("%d/%m/%Y-%H:%M:%S")
        read1 = self.status.toPlainText()
        self.status.setText(text+" >>> "+time_print+" \n"+ read1+" ")

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    # app.exec_()
    sys.exit(app.exec_())

In your case we must create a function that stores the attributes in the MailSender class, for example:

class MailSender(QtCore.QThread):
    newMessage = QtCore.pyqtSignal(str)
    def __init__(self, , parent=None):
        QtCore.QThread.__init__(self, parent)

    def setData(self, server, user, pass1):
        self.server = server
        self.user = user
        self.pass1 = pass1

Then in the run_mail_class function you must call that function before starting the thread.

def run_mail_class(self):
    self.myThread1.setData(server,user, pass1)
    self.myThread1.start()

When you want to access the values in the method mail_send you must do it through the attribute for example:

conn = SMTP(str(self.server))
conn.login(str(self.user), str(self.pass1))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM