Hello, I am creating a GUI program with PyQt4 in python. The purpose is to be an efficiency tool for my company. I have a GUI, but put all the code in one thread. I have not dealt with threads yet and after 2 weeks of reading up, I still can not figure it out with my code. The issue at hand is that I would like to hide the console window while still displaying some outputs to keep track of processes. I was trying to use self.textEdit.append to achieve this, but because it is all in one thread, the outputs all post after the process is done. I know I need threads, I just cant figure out how to apply it to my code.

The gui I got from QTdesigner and added the run method. Could you give me some guidance on how to implement QThread in my program? Any would help. I am at the end of my coding rope. Thank You!

here is my abridged code:

from PyQt4 import QtCore, QtGui
import socket
from binascii import hexlify
import os
import sys, string, telnetlib, time
import csv, datetime, io
import urllib.request

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(595, 252)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.tabWidget = QtGui.QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 591, 121))
        self.tabWidget.setTabPosition(QtGui.QTabWidget.North)
        self.tabWidget.setTabShape(QtGui.QTabWidget.Rounded)
        self.tabWidget.setElideMode(QtCore.Qt.ElideNone)
        self.tabWidget.setUsesScrollButtons(True)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))

.
.
.*GUI Stuff in the tabs..
.
.
.

self.pushButtonRUN = QtGui.QPushButton(self.centralwidget)
        self.pushButtonRUN.setGeometry(QtCore.QRect(490, 130, 91, 21))
        self.pushButtonRUN.setObjectName(_fromUtf8("pushButtonRUN"))
        self.pushButtonRUN.clicked.connect(self.Run)#



    self.labelPATH = QtGui.QLabel(self.centralwidget)
    self.labelPATH.setGeometry(QtCore.QRect(10, 130, 91, 21))
    self.labelPATH.setObjectName(_fromUtf8("labelPATH"))

    self.linePATH = QtGui.QLineEdit(self.centralwidget)
    self.linePATH.setGeometry(QtCore.QRect(100, 130, 291, 21))
    self.linePATH.setObjectName(_fromUtf8("linePATH"))

    self.pushButtonPATH = QtGui.QPushButton(self.centralwidget)
    self.pushButtonPATH.setGeometry(QtCore.QRect(400, 130, 75, 21))
    self.pushButtonPATH.setObjectName(_fromUtf8("pushButtonPATH"))
    self.pushButtonPATH.clicked.connect(self.selectPath)#

    self.textEdit = QtGui.QTextEdit(self.centralwidget)
    self.textEdit.setGeometry(QtCore.QRect(20, 160, 551, 71))
    self.textEdit.setObjectName(_fromUtf8("textEdit"))

    MainWindow.setCentralWidget(self.centralwidget)

    self.statusbar = QtGui.QStatusBar(MainWindow)
    self.statusbar.setObjectName(_fromUtf8("statusbar"))

    MainWindow.setStatusBar(self.statusbar)

    self.actionExit = QtGui.QAction(MainWindow)
    self.actionExit.setObjectName(_fromUtf8("actionExit"))

    self.retranslateUi(MainWindow)
    self.tabWidget.setCurrentIndex(0)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)



def retranslateUi(self, MainWindow):

.
.
.set labels and such
.

def selectPath(self):
        self.filedialog = QtGui.QFileDialog()
        filepath = str(self.filedialog.getExistingDirectory())
        self.linePATH.setText(filepath)

def Run(self):

.
.
.big if/elif statement for each tab performance... example of one below:

    elif self.tabWidget.currentIndex() == 1 :
        print("Fetching AAA Data...")
        AAAIP = self.lineAAAIP.text()
        AAAport = self.lineAAAport.text()
        AAACMD = self.lineAAACMD.text()
        addressAAA = 'http://' + AAAIP + ':' + AAAport +'/' + AAACMD + '.csv'
        htmlMRC = urllib.request.urlopen(addressAAA).read()
        f = open(self.linePATH.text() + '/' + AAAIP + '-' + AAAport + '.csv', 'wb')
        f.write(htmlAAA)
        f.close()
        print('File saved to ' + self.linePATH.text() + ' as ' + AAAIP + '-' + AAAport + '.csv')
        self.textEdit.append(_translate("MainWindow", ">>> Download complete and Files saved to " + self.linePATH.text(), None))###
        print("Done.")

.
.

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()



sys.exit(app.exec_())

Here is an example ....

''' pqt_thread_test102.py
test Qthread threading
time delay works properly

modified from ...
http://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/
'''

import sys, time
from PyQt4 import QtCore, QtGui

class GenericThread(QtCore.QThread):
    def __init__(self, function, *args, **kwargs):
        QtCore.QThread.__init__(self)
        self.function = function
        self.args = args
        self.kwargs = kwargs

    def __del__(self):
        self.wait()

    def run(self):
        self.function(*self.args, **self.kwargs)
        return


class MyApp(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.threadPool = []

        self.setGeometry(300, 300, 280, 420)
        self.setWindowTitle('QThread test')

        self.layout = QtGui.QVBoxLayout(self)

        self.testButton = QtGui.QPushButton("test")
        self.connect(self.testButton, QtCore.SIGNAL("released()"),
                     self.test)
        self.listwidget = QtGui.QListWidget(self)

        self.layout.addWidget(self.testButton)
        self.layout.addWidget(self.listwidget)

    def add(self, text):
        """ Add item to list widget """
        #print("Add: " + text)  # test print
        self.listwidget.addItem(text)
        self.listwidget.sortItems()

    def addBatch(self, text="test", iters=10, delay=1.5):
        """ Add several items to list widget """
        for i in range(1, iters):
            # time delay works best with threading
            time.sleep(delay)
            self.add(text + " " + str(i))

    def test(self):
        self.listwidget.clear()
        # apply threading to self.addBatch()
        self.genericThread = GenericThread(self.addBatch,
                                "using generic thread ", delay=0.5)
        self.genericThread.start()


app = QtGui.QApplication(sys.argv)
test = MyApp()
test.show()
app.exec_()

@vegaseat

I get the example, I think I am just overwhelmed with my code. Is it as simple as replacing my "run" with the examples' and adding the thread class? If someone could give some guidance on how it would apply to my code I would be greatful. I have been working on this example for a few days now and can not seem to get it to mesh with my code.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.