Attempting to write a class that will show the progress of a threaded process. I need to use this class for all "file load" operations; however I am having trouble making it global.
fileloader.py:
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QDialog
from PyQt5.uic import loadUi
class FileLoader(QDialog):
completeSig = pyqtSignal()
def __init__(self, parent=None):
super(FileLoader, self).__init__(parent)
self.filename = ""
self.clientcode = ""
self.thread = ""
loadUi("GlobalUI/fileloader.ui", self)
self.prgLoader.setValue(0)
#pyqtSlot()
def on_btnCancel_clicked(self):
self.close()
def closeEvent(self, e):
self.thread.stop()
def loadData(self):
self.thread.totalSig.connect(self.prgLoader.setMaximum)
self.thread.countSig.connect(self.prgLoader.setValue)
self.thread.finished.connect(self.completed)
self.thread.start()
def completed(self):
self.completeSig.emit()
self.close()
loader.py
from PyQt5.QtCore import pyqtSignal, QThread
from fileloader import FileLoader
class DataLoader(QThread):
totalSig = pyqtSignal(int)
countSig = pyqtSignal(int)
def __init__(self, parent=None):
super(DataLoader, self).__init__(parent)
self.threadactive = True
self.commitsize = 300
self.rowdata = []
def run(self):
print("Code Will Go Here For Loading the File")
def stop(self):
self.threadactive = False
self.wait()
class PatDataLoader():
def load(self, clientcode, filename):
fl = FileLoader()
fl.clientcode = clientcode
fl.filename = filename
fl.thread = DataLoader()
fl.loadData()
I am calling PatDataLoader.load("test","test.txt") from another module. The problem I am running into is the application crashes with QThread: Destroyed while thread is still running as there seems to be a problem with the thread process I am passing to the fileloader. Am I not putting these pieces together properly?
main.py:
from lmdb.patloader import PatDataLoader
class PPSReportsApp(QMainWindow):
def __init__(self, *args):
super(PPSReportsApp, self).__init__(*args)
loadUi("GlobalUI/ppsreportswindow.ui", self)
#self.showMaximized()
#pyqtSlot()
def on_actionTest_triggered(self):
pl = PatDataLoader()
pl.load("TEST","testfile.txt")
In your code pl is a local variable so it will be deleted when it finishes executing on_actionTest_triggered which is an instant possibly generating that problem. On the other hand, no load should be a static method because it does not use the self. self.thread must be None, it is better than ""
How can you prevent pl from being deleted before it is finished processing?
fl is a QDialog so you can use exec_().
fileloader.py
class FileLoader(QDialog):
completeSig = pyqtSignal()
def __init__(self, parent=None):
super(FileLoader, self).__init__(parent)
self.filename = ""
self.clientcode = ""
self.thread = None
loadUi("GlobalUI/fileloader.ui", self)
self.prgLoader.setValue(0)
#pyqtSlot()
def on_btnCancel_clicked(self):
self.close()
def closeEvent(self, e):
if self.thread:
self.thread.stop()
def loadData(self):
if self.thread:
self.thread.totalSig.connect(self.prgLoader.setMaximum)
self.thread.countSig.connect(self.prgLoader.setValue)
self.thread.finished.connect(self.completed)
self.thread.start()
def completed(self):
self.completeSig.emit()
self.close()
loader.py
class DataLoader(QThread):
totalSig = pyqtSignal(int)
countSig = pyqtSignal(int)
def __init__(self, parent=None):
super(DataLoader, self).__init__(parent)
self.threadactive = True
self.commitsize = 300
self.rowdata = []
def run(self):
self.totalSig.emit(1000)
print("Code Will Go Here For Loading the File")
# emulate process
for i in range(1000):
if self.threadactive:
QThread.msleep(10)
self.countSig.emit(i)
def stop(self):
self.threadactive = False
self.quit()
self.wait()
class PatDataLoader():
#staticmethod
def load(clientcode, filename):
fl = FileLoader()
fl.clientcode = clientcode
fl.filename = filename
fl.thread = DataLoader()
fl.loadData()
fl.exec_() # <---
main.py
#pyqtSlot()
def on_actionTest_triggered(self):
PatDataLoader.load("TEST","testfile.txt")
Related
I have the following code but it's complaining that I cannot access the UI data from my thread. In my example code below, What is the best way I can access the userInputString value so my threading can run?
self.nameField is a PyQt QLineEdit.
QObject::setParent: Cannot set parent, new parent is in a different thread
QPixmap: It is not safe to use pixmaps outside the GUI thread
QWidget::repaint: Recursive repaint detected
import myUI
class MainUIClass(QtGui.QMainWindow, myUI.Ui_MainWindow):
def __init__(self, parent=None):
super(MainUIClass, self).__init__(parent)
self.setupUi(self)
self.startbutton.clicked.connect(self.do_work)
self.workerThread = WorkerThread()
self.connect(self.workerThread, SIGNAL("myThreading()"), self.myThreading, Qt.DirectConnection)
def do_work(self):
self.userInputString = self.nameField.Text()
self.workerThread.start()
def myThreading(self):
if userInputString is not None:
#Do something
class WorkerThread(QThread):
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
def run(self):
self.emit(SIGNAL("myThreading()"))
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
app = MainUIClass()
app.show()
a.exec_()
Not sure if it's what you need but here is a working QThread exemple using Qt5
import time
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.worker_thread = WorkerThread()
self.worker_thread.job_done.connect(self.on_job_done)
self.create_ui()
def create_ui(self):
self.button = QtWidgets.QPushButton('Test', self)
self.button.clicked.connect(self.start_thread)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
def start_thread(self):
self.worker_thread.gui_text = self.button.text()
self.worker_thread.start()
def on_job_done(self, generated_str):
print("Generated string : ", generated_str)
self.button.setText(generated_str)
class WorkerThread(QtCore.QThread):
job_done = QtCore.pyqtSignal('QString')
def __init__(self, parent=None):
super(WorkerThread, self).__init__(parent)
self.gui_text = None
def do_work(self):
for i in range(0, 1000):
print(self.gui_text)
self.job_done.emit(self.gui_text + str(i))
time.sleep(0.5)
def run(self):
self.do_work()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
test = MainWindow()
test.show()
app.exec_()
when clicking a button in the PyQt5 Ui iam starting a mitmproxy. When the proxy is started, i try to change a listWidget with Data from the Proxy.
main.py
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from MainWindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, obj=None, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setupUi(self)
self.pushButton.clicked.connect(self.Start)
def Start(self):
x = threading.Thread(target=self.StartMITM)
x.start()
def StartMITM(self):
os.system("mitmweb -s mitmproxy.py -q --no-web-open-browser")
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
mitmproxy.py - this is the error part
from mitmproxy import http
from main import MainWindow
def response(flow):
MainWindow.listWidget.addItem(flow.request.pretty_url)
Can I connect to the Widgets from another File?
It has 2 independent processes: The GUI and the mitmproxy script. And communicating both processes does not imply importing modules since you would be creating another widget, also objects should not be accessed through classes (I recommend you check your basic python notes).
In this the solution is to use some Inter process communication (IPC), in this case you can use Qt Remote Objects (QtRO):
main.py
from functools import cached_property
from PyQt5 import QtCore, QtRemoteObjects, QtWidgets
class Bridge(QtCore.QObject):
messageChanged = QtCore.pyqtSignal(str)
#QtCore.pyqtSlot(str)
def add_message(self, message):
self.messageChanged.emit(message)
class MitmwebManager(QtCore.QObject):
logChanged = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
# self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
self.process.readyReadStandardOutput.connect(self.handle_log)
self.process.setProgram("mitmweb")
#cached_property
def process(self):
return QtCore.QProcess()
def start(self, arguments):
self.process.setArguments(arguments)
self.process.start()
def stop(self):
self.process.kill()
def handle_log(self):
data = self.process.readAllStandardOutput()
codec = QtCore.QTextCodec.codecForName("UTF-8")
message = codec.toUnicode(data)
self.logChanged.emit(message)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.button = QtWidgets.QPushButton("Start", checkable=True)
self.listwidget = QtWidgets.QListWidget()
self.logview = QtWidgets.QPlainTextEdit(readOnly=True)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QGridLayout(central_widget)
lay.addWidget(self.button, 0, 0, 1, 2)
lay.addWidget(self.listwidget, 1, 0)
lay.addWidget(self.logview, 1, 1)
self.register_node = QtRemoteObjects.QRemoteObjectRegistryHost(
QtCore.QUrl("local:registry")
)
self.source_node = QtRemoteObjects.QRemoteObjectHost(
QtCore.QUrl("local:replica"), QtCore.QUrl("local:registry")
)
self.source_node.enableRemoting(self.bridge, "bridge")
self.button.toggled.connect(self.handle_toggled)
self.mitmweb.logChanged.connect(self.handle_log_changed)
self.bridge.messageChanged.connect(self.handle_message_changed)
self.resize(640, 480)
#cached_property
def mitmweb(self):
return MitmwebManager()
#cached_property
def bridge(self):
return Bridge()
def handle_toggled(self, checked):
if checked:
self.mitmweb.start(["-s", "script.py", "--no-web-open-browser"])
self.button.setText("Stop")
else:
self.mitmweb.stop()
self.button.setText("Start")
def handle_log_changed(self, message):
self.logview.insertPlainText(message)
def closeEvent(self, event):
super().closeEvent(event)
self.mitmweb.stop()
def handle_message_changed(self, message):
item = QtWidgets.QListWidgetItem(message)
self.listwidget.addItem(item)
def main():
app = QtWidgets.QApplication([])
view = MainWindow()
view.show()
app.exec_()
if __name__ == "__main__":
main()
script.py
from mitmproxy import http
from PyQt5 import QtCore, QtRemoteObjects
class Bridge(QtCore.QObject):
def __init__(self, bridge, parent=None):
super().__init__(parent)
self._message = ""
self._bridge = bridge
self.bridge.initialized.connect(self.handle_initialized)
#property
def bridge(self):
return self._bridge
#property
def message(self):
return self._message
def send_message(self, message):
self._message = message
#QtCore.pyqtSlot()
def handle_initialized(self):
self.bridge.add_message(self._message)
QtCore.QTimer.singleShot(0, QtCore.QCoreApplication.quit)
def send_qt(message):
qt_app = QtCore.QCoreApplication([])
replica_node = QtRemoteObjects.QRemoteObjectNode(QtCore.QUrl("local:registry"))
replica_bridge = replica_node.acquireDynamic("bridge")
bridge = Bridge(replica_bridge)
bridge.send_message(message)
qt_app.exec_()
def response(flow):
send_qt(flow.request.pretty_url)
I want to use multiple imported function with arguments that takes some while to run. I want a 'working' progress bar that track the processes of that function. I have followed 2 questions already here.
Connect an imported function to Qt5 progress bar without dependencies
Report progress to QProgressBar using variable from an imported module
The difference is that the thread can take any function which can have arguments. The function also not needs to yield the percent to return to the progressbar. The progressbar always start at 0%.
I copied a snippet from first link and modified it for example purpose.
from external_script import long_running_function
class Actions(QDialog):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Progress Bar')
self.progress = QProgressBar(self)
self.button = QPushButton('Start', self)
self.show()
self.button.clicked.connect(self.onButtonClick)
def onButtonClick(self):
long_running_function(**kwargs) # This can be any function that takes argument/s
self.progress.setValue(value)
Do not get too complicated with the answers as they are limited to a very particular context. In general the logic is to pass a QObject to it that updates the percentage value and then emits a signal with that value. For example a simple solution is to use the threading module:
import sys
import threading
from PyQt5 import QtCore, QtWidgets
class PercentageWorker(QtCore.QObject):
started = QtCore.pyqtSignal()
finished = QtCore.pyqtSignal()
percentageChanged = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
self._percentage = 0
#property
def percentage(self):
return self._percentage
#percentage.setter
def percentage(self, value):
if self._percentage == value:
return
self._percentage = value
self.percentageChanged.emit(self.percentage)
def start(self):
self.started.emit()
def finish(self):
self.finished.emit()
class FakeWorker:
def start(self):
pass
def finish(self):
pass
#property
def percentage(self):
return 0
#percentage.setter
def percentage(self, value):
pass
import time
def long_running_function(foo, baz="1", worker=None):
if worker is None:
worker = FakeWorker()
worker.start()
while worker.percentage < 100:
worker.percentage += 1
print(foo, baz)
time.sleep(1)
worker.finish()
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.progress = QtWidgets.QProgressBar()
self.button = QtWidgets.QPushButton("Start")
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.button)
lay.addWidget(self.progress)
self.button.clicked.connect(self.launch)
def launch(self):
worker = PercentageWorker()
worker.percentageChanged.connect(self.progress.setValue)
threading.Thread(
target=long_running_function,
args=("foo",),
kwargs=dict(baz="baz", worker=worker),
daemon=True,
).start()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
I need to create a custom signal on Qmdisubwindow close. In other word, when I closed any subwindow, a signal is emitted with the name of that window being closed. Below is my trail, but seems not right. Error occurs as:
a subwindow already created without calling
add subwindow option is not working
closable action is not working
Hope you can show me how to fix it.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyMdi(QMdiSubWindow):
sigClosed = pyqtSignal(str)
def __init__(self, parent=None):
super(MyMdi, self).__init__(parent)
def closeEvent(self, event):
"""Get the name of active window about to close
"""
name = name
self.sigClosed.emit('{} is close'.format(name))
QMdiSubWindow.closeEvent(self, event)
class MainWindow(QMainWindow):
count = 0
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
self.mdi = MyMdi()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
file.triggered[QAction].connect(self.windowaction)
self.setWindowTitle("MDI demo")
# my signal
self.mdi.sigClosed.connect(self.windowclosed)
#pyqtSlot(str)
def windowclosed(self, text):
print(text)
def windowaction(self, q):
if q.text() == "New":
MainWindow.count = MainWindow.count+1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("subwindow"+str(MainWindow.count))
self.mdi.addSubWindow(sub)
sub.show()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
You have an initial error: a QMdiSubWindow must be inside a QMdiArea but there is none in your code.
On the other hand, the idea of subclassing is good but you have several drawbacks:
You are not using it initially since there is no QMdiArea, if you execute the QAction then your application will be closed because a QMdiSubWindow does not have any method called addSubWindow.
The QMdiSubWindow does not have an attribute called name, you must use windowTitle.
class MdiSubWindow(QMdiSubWindow):
sigClosed = pyqtSignal(str)
def closeEvent(self, event):
"""Get the name of active window about to close
"""
self.sigClosed.emit(self.windowTitle())
QMdiSubWindow.closeEvent(self, event)
class MainWindow(QMainWindow):
count = 0
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("File")
file.addAction("New")
file.triggered[QAction].connect(self.windowaction)
self.setWindowTitle("MDI demo")
#pyqtSlot(str)
def windowclosed(self, text):
print(text)
def windowaction(self, q):
if q.text() == "New":
MainWindow.count = MainWindow.count + 1
sub = MdiSubWindow()
sub.setWidget(QTextEdit())
sub.setAttribute(Qt.WA_DeleteOnClose)
sub.setWindowTitle("subwindow" + str(MainWindow.count))
sub.sigClosed.connect(self.windowclosed)
self.mdi.addSubWindow(sub)
sub.show()
I'm writing an UI using QT5 and python, I added a thread to handle the UI, thread works "fine", a function inside the thread receive 2 strings and return 2 strings (I'm making experiments before develop the real project just to see how it works), as you can see in the code after call the thread function with:
self.requestConexion.emit('lblText1','dddddd')
I call another function that is just a simple counter
self.contador()
so I expect that before the counter finish the value of the control self.lblText1 change, but this is not happen... here is the main code:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import UI_test
import time
import sys
class Threaded(QObject):
result=pyqtSignal(str,str)
def __init__(self, parent=None, **kwargs):
super().__init__(parent, **kwargs)
#pyqtSlot(str,str)
def etiquetas(self,lbl,texto):
print(texto)
self.result.emit(lbl,texto)
class MainApp(QMainWindow, UI_test.Ui_MainWindow):
requestConexion=pyqtSignal(str,str)
def __init__(self, parent=None):
super(MainApp, self).__init__(parent)
self._thread=QThread()
self._threaded=Threaded(result=self.displayLabel)
self.requestConexion.connect(self._threaded.etiquetas)
self._threaded.moveToThread(self._thread)
qApp.aboutToQuit.connect(self._thread.quit)
self._thread.start()
self.setupUi(self)
self.btnStart.clicked.connect(self.conexion)
#pyqtSlot()
def conexion(self):
#self._thread.start()
print(1)
self.requestConexion.emit('lblText1','dddddd')
self.contador()
text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')
if ok:
print(str(text))
#pyqtSlot()
def contador(self):
i=0
while i<50:
print(i)
time.sleep(0.1)
i+=1
#pyqtSlot(str,str)
def displayLabel(self, etiqueta, texto):
self.lblText1.setText(etiqueta)
print(texto)
def main():
app = QApplication(sys.argv)
form = MainApp()
form.show()
app.exec_()
exit(app.exec_())
if __name__ == '__main__':
main()
any idea whats wrong?
I finally find the answer to my question in the next blog:
https://martinfitzpatrick.name/article/multithreading-pyqt-applications-with-qthreadpool/
this is a really great tutorial, after read the documentation in the blog I was able to modify one of the examples to modify the text of a label control in real time; here is the final code:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
class Worker(QRunnable):
def __init__(self, fn, *args, **kwargs):
super(Worker, self).__init__()
self.args = args
self.kwargs = kwargs
self.fn = fn
#pyqtSlot()
def run(self):
#print(self.args, self.kwargs)
print("Thread start")
time.sleep(0.2)
self.fn(*self.args, **self.kwargs) #ejecuta la funcion recibida
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.threadpool = QThreadPool()
print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())
self.counter = 0
layout = QVBoxLayout()
self.l = QLabel("Start")
self.l2 = QLabel("xxxxx")
b = QPushButton("DANGER!")
b.pressed.connect(self.oh_no)
layout.addWidget(self.l)
layout.addWidget(self.l2)
layout.addWidget(b)
w = QWidget()
w.setLayout(layout)
self.setCentralWidget(w)
self.show()
self.etiqueta="rrrrrrrrrr"
self.timer = QTimer()
self.timer.setInterval(500)
self.timer.timeout.connect(self.recurring_timer)
self.timer.start()
def oh_no(self):
self.etiqueta="hhhhhhhhhhhhhhhhh"
worker = Worker(self.execute_this_fn,'4444')
self.threadpool.start(worker)
def recurring_timer(self):
self.counter +=1
self.l.setText("Counter: %d" % self.counter)
def execute_this_fn(self,x):
print("Hello!")
self.l2.setText(x)
app = QApplication([])
window = MainWindow()
app.exec_()