Need Advice To Keep Gui Responsive
Basically, what I have is a GUI with some QLineEdits, a 'search button' and a table. You hit the button and a class called DataGrabber searches a database for data, processes them,
Solution 1:
This can be handled with signals. You can use signals to send the results to the GUI and to update the GUI of the progress.
Here is a quick example of the implementation with a progress bar and status label. These can be included in a status bar if you would like:
classGUITest(QtWidgets.QWidget):
def__init__(self):
QtWidgets.QWidget.__init__(self)
layout = QtWidgets.QGridLayout()
self.button = QtWidgets.QPushButton('Run')
self.button.clicked.connect(self.run)
self.result_box = QtWidgets.QTextBrowser()
self.label = QtWidgets.QLabel()
self.progress_bar = QtWidgets.QProgressBar()
self.progress_bar.setVisible(False)
self.progress_bar.setMinimum(0)
self.progress_bar.setMaximum(100)
self.progress_bar.setValue(0)
layout.addWidget(self.button)
layout.addWidget(self.result_box)
layout.addWidget(self.label)
layout.addWidget(self.progress_bar)
self.setLayout(layout)
defrun(self):
self.progress_bar.setVisible(True)
self.label.setText('Searching...')
self.thread = QtCore.QThread()
self.data_grabber = DataGrabber()
self.data_grabber.moveToThread(self.thread)
self.data_grabber.update_progress.connect(self.update_progress_bar)
self.data_grabber.results.connect(self.display_results)
self.data_grabber.finished.connect(self.complete)
self.data_grabber.finished.connect(self.thread.quit)
self.data_grabber.finished.connect(self.data_grabber.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.thread.started.connect(self.data_grabber.run)
self.thread.start()
defupdate_progress_bar(self):
self.progress_bar.setValue(self.progress_bar.value() + 1)
defcomplete(self):
self.label.setText('Complete')
self.progress_bar.setVisible(False)
defdisplay_results(self, results):
for key, value in results.items():
self.result_box.append('%s: %s' % (key, value))
classDataGrabber(QtCore.QObject):
finished = QtCore.pyqtSignal()
update_progress = QtCore.pyqtSignal()
results = QtCore.pyqtSignal(dict) # set the type of object you are sendingdef__init__(self):
super().__init__()
self.count = 0defrun(self):
# search database here and emit update_progress when appropriatewhile self.count <= 100:
self.update_progress.emit()
self.count += 1
time.sleep(0.02)
self.send_results() # when done, send the results
self.finished.emit()
defsend_results(self):
results = {'one': 'Result One', 'two': 'Result Two', 'three': 'Result Three'}
self.results.emit(results)
Post a Comment for "Need Advice To Keep Gui Responsive"