Saving the value in case of multithreading - python

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, os, time
import Queue
import threading
import subprocess
class LearnButton(QPushButton):
def __init__(self, title, test):
super(QPushButton, self).__init__()
self._title = title
self._test = test
self.setText(title)
self.clicked.connect(self.click_threads)
self._q = Queue.Queue()
self.flag = True
def click_threads(self):
self.thread1 = threading.Thread(target=self.fun1)
self.thread2 = threading.Thread(target=self.fun2)
self.thread1.start()
self.thread2.start()
def fun1(self):
print "Val", self._test, self._title, type(self._test), type(self._title)
if self._test != "None":
self.date_time_string = time.strftime("%Y%m%d_%H%M%S")
self.retainedv = self.date_time_string
print self.date_time_string
self.flag = False
else:
print self.retainedv
def fun2(self):
print "Val", self._test, self._title, type(self._test), type(self._title)
self.setEnabled(False)
if self._test != "None":
while self.thread1.isAlive():
self.setText('h')
time.sleep(0.5)
self.setText('i')
time.sleep(0.5)
self.setText('i')
time.sleep(0.5)
self.setEnabled(True)
self.setText(self._title)
else:
self.setEnabled(True)
class LearnApp(QDialog):
def __init__(self):
super(QDialog, self).__init__()
self.setWindowTitle("LearnApp")
self.active = False
close_button = QPushButton("Close")
close_button.clicked.connect(self.close)
self.button1 = LearnButton("B1", "Im in B1")
self.button2 = LearnButton("B2", "Im in B2")
self.button3 = LearnButton("B3", "Im in B3")
self.check_button = LearnButton("Check", "None")
self.test_report = QTextEdit()
self.test_report.setReadOnly(True)
layout = QHBoxLayout()
sub_layout = QVBoxLayout()
sub_layout.addWidget(self.button1)
sub_layout.addWidget(self.button2)
sub_layout.addWidget(self.button3)
sub_layout.addWidget(self.check_button)
sub_layout.addWidget(close_button)
layout.addLayout(sub_layout)
layout.addWidget(self.test_report)
self.setLayout(layout)
self.setFocus()
app = QApplication(sys.argv)
dialog = LearnApp()
dialog.show()
app.exec_()
This is the code I'm trying to modify. Theme is after pressing B1, B2 or B3, I want to write the value of date_time_string to the text block.
Value of date_time_string shouldn't be calculated at the time when we press 'Check'.
Pressiing B1, calculates the value of date_time_string and after that what I'm trying to do is clicking 'Check' and writing the value of 'date_time_string' from the previous click (that is when B1 was clicked) to the text box.
Is there any way to retain the value of date_time_string for the next click?
Thanks

Related

How to change images with key press events in PyQt5, python

I just want to show different images whenever I press keys.
Different keys are connected to different functions which show different image or do different things.
There is text at first, and after press spacebar key, the text is deleted and 'image 1' is appeared. I want to change image which is shown on screen whenever I press the keyboard button 'F' or 'J'
, but nothing is happened after I press space bar key.
Here are my codes below.
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
class StartExp(QWidget):
def __init__(self):
super().__init__()
self.expUI()
def expUI(self):
self.setWindowTitle("ver.1")
self.resize(500, 500)
self.information()
def information(self):
# information
self.info1 = QLabel(f"Hi, there!", self)
self.info1.setAlignment(Qt.AlignCenter)
layout = QVBoxLayout()
layout.addWidget(self.info1)
self.setLayout(layout)
def image1(self):
fix_h = 100
fix_w = 100
self.img1 = QLabel(self)
image1 = QPixmap('1.jpg')
self.img1.setPixmap(image1)
self.img1.move(fix_w, fix_h)
def image2(self):
fix_h = 100
fix_w = 100
self.img2 = QLabel(self)
image2 = QPixmap('2.jpg')
self.img2.setPixmap(image2)
self.img2.move(fix_w, fix_h)
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
elif e.key() ==Qt.Key_F:
self.clearimage2()
self.image1()
self.update()
elif e.key() ==Qt.Key_J:
self.clearimage1()
self.image2()
self.update()
elif e.key() == Qt.Key_Space:
self.clearinfo()
self.image1()
self.update()
def clearinfo(self):
try:
self.info1.clear()
except:
pass
def clearimage1(self):
try:
self.info1.clear()
except:
pass
def clearimage2(self):
try:
self.image2.clear()
except:
pass
def run():
app = QApplication(sys.argv)
mainExp = StartExp()
sys.exit(app.exec_())
run()

PyQt4 - QLineEdit() and QCheckbox()

I am building a GUI for obtaining user inputs and then using them in some complex step later. I have a group of checkboxes from which the user has to choose at least one and also provide an 'alias' name for it in the QLineEdit right below the checkbox (default name is taken otherwise).
Currently, I have to first enter the alias name and then check the checkbox to register the entered name in the line edit to get the value entered by the user and connected checkbox name. This order is not normal.
Is there a way to get the Editline data and the connected checkbox name when 'Continue' is clicked?
Here is my code:
from PyQt4 import QtGui, QtCore
import sys
checkpoint_list = ['Amsterdam','Munich','Paris','Mumbai']
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
self.final_list = []
self.platform_list = {}
self.qem = None
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:", self)
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
i = 0
for cp in checkpoint_list:
self.cb.append(QtGui.QCheckBox(cp, self))
self.platform_label.append(QtGui.QLineEdit(cp, self))
self.cb[i].stateChanged.connect(self.clickBoxStateChanged)
lay_out.addWidget(self.cb[i])
lay_out.addWidget(self.platform_label[i])
i += 1
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton('Cancel', self)
btn_continue = QtGui.QPushButton('Continue', self)
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
self.setLayout(lay_out)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip('To <b>Cancel</b> with this process')
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip('To <b>Continue</b> with the matching')
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle('CP Selection Window')
self.show()
def clickBoxStateChanged(self, cb):
self.final_list = []
self.platform_list = {}
for i in range(len(self.cb)):
if self.cb[i].isChecked():
if self.cb[i] not in self.final_list:
self.final_list.append(str(self.cb[i].text()))
self.platform_list[str(self.cb[i].text())] = str(self.platform_label[i].text())
print self.final_list
print self.platform_list
elif self.cb[i].isChecked() == False:
if self.cb[i].text() in self.final_list:
self.final_list.remove(str(self.cb[i].text()))
del self.platform_list[str(self.cb[i].text())]
print self.final_list
print self.platform_list
def onclick_Continue(self):
try:
if len(self.final_list) == 0:
self.qem = QtGui.QErrorMessage(self)
self.qem.showMessage("Please select at least 1 checkpoint to continue...")
else:
self.close()
except:
print "No CP was selected..."
def onclick_cancel(self):
sys.exit()
if __name__ == "__main__":
# GUI code
app = QtGui.QApplication(sys.argv)
w = MyGui()
app.exec_()
The simplest solution is to create a method that analyzes the information and that returns a dictionary of the selected elements:
class MyGui(QtGui.QWidget):
def __init__(self):
super(MyGui, self).__init__()
self.initUI()
def initUI(self):
lay_out = QtGui.QVBoxLayout(self)
# select the CPs
cp_lbl = QtGui.QLabel("Please select CP versions to compare:")
lay_out.addWidget(cp_lbl)
self.cb = []
self.platform_label = []
for cp in checkpoint_list:
cb = QtGui.QCheckBox(cp)
le = QtGui.QLineEdit(cp)
lay_out.addWidget(cb)
lay_out.addWidget(le)
self.cb.append(cb)
self.platform_label.append(le)
lay_out.addStretch(10)
# Continue and cancel button
btn_cancel = QtGui.QPushButton("Cancel")
btn_continue = QtGui.QPushButton("Continue")
hbox = QtGui.QHBoxLayout()
hbox.addStretch()
hbox.addWidget(btn_continue)
hbox.addWidget(btn_cancel)
vbox = QtGui.QVBoxLayout()
vbox.addStretch()
lay_out.addLayout(hbox)
lay_out.addLayout(vbox)
btn_cancel.clicked.connect(self.onclick_cancel)
btn_cancel.setToolTip("To <b>Cancel</b> with this process")
btn_continue.clicked.connect(self.onclick_Continue)
btn_continue.setToolTip("To <b>Continue</b> with the matching")
# Screen show
self.setGeometry(300, 300, 500, 400)
self.setWindowTitle("CP Selection Window")
self.show()
def get_elements_selected(self):
values_selected = dict()
for cb, le in zip(self.cb, self.platform_label):
if cb.isChecked():
values_selected[cb.text()] = le.text()
return values_selected
def onclick_Continue(self):
values = self.get_elements_selected()
if values:
print(values)
self.close()
else:
qem = QtGui.QErrorMessage(self)
qem.showMessage("Please select at least 1 checkpoint to continue...")
qem.exec_()
def onclick_cancel(self):
sys.exit()

How to update a AnimationGroup without creating a new AnimationGroup every time?

I want to run a AnimationGroup with different changing animations.
But the problem is that the function clear()
self.group = QtCore.QSequentialAnimationGroup(self)
def anim(self):
if X == True:
self.group.addAnimation(self.animation_1)
self.group.addAnimation(self.animation_2)
elif X == False:
self.group.addAnimation(self.animation_3)
self.group.addAnimation(self.animation_4)
self.group.start()
self.group.clear()
displays an error
RuntimeError: wrapped C/C++ object of type QVariantAnimation has been deleted
I can’t constantly create a new group.
def anim(self):
self.group = QtCore.QSequentialAnimationGroup(self)
if X == True:
self.group.addAnimation(self.animation_1)
self.group.addAnimation(self.animation_2)
elif X == False:
self.group.addAnimation(self.animation_3)
self.group.addAnimation(self.animation_4)
self.group.start()
self.group.clear()
I tried to use removeAnimation
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class Rad(QtWidgets.QWidget):
def __init__(self, group, pos, parent=None):
super(Rad, self).__init__(parent)
self.resize(50, 50)
lay = QtWidgets.QVBoxLayout(self)
self.radio = QtWidgets.QRadioButton()
self.label = QtWidgets.QLabel()
self.label.setText('but-{}'.format(pos))
self.group = group
self.pos = pos
lay.addWidget(self.radio)
lay.addWidget(self.label)
self.radio.toggled.connect(self.fun)
self.animation = QtCore.QVariantAnimation()
self.animation.setDuration(1000)
self.animation.valueChanged.connect(self.value)
self.animation.setStartValue(100)
self.animation.setEndValue(0)
self.can = False
def value(self, val):
self.move(self.pos, val)
def fun(self):
self.animation.setStartValue(
100
if not self.can
else 0
)
self.animation.setEndValue(
0
if not self.can
else 100
)
if self.group.animationAt(1) == None :
print("Bad")
else :
print("Good")
self.group.removeAnimation(self.group.animationAt(0))
self.group.addAnimation(self.animation)
self.group.start()
self.can = not self.can
class Test(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.group = QtCore.QSequentialAnimationGroup(self)
self.buts = QtWidgets.QButtonGroup(self, exclusive=True)
wid_1 = Rad(self.group, 200, self)
wid_2 = Rad(self.group, 100, self)
wid_3 = Rad(self.group, 0, self)
self.buts.addButton(wid_1.radio, 0)
self.buts.addButton(wid_2.radio,1)
self.buts.addButton(wid_3.radio, 2)
wid_1.setStyleSheet('background:brown;')
wid_2.setStyleSheet('background:yellow;')
wid_3.setStyleSheet('background:green;')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Test()
w.resize(500, 500)
w.show()
sys.exit(app.exec_())
And now the animation has become sharp
And in the console output
QAnimationGroup::animationAt: index is out of bounds
From what I can deduce is that you want the pressed item to move down and if any item was in the low position then it must return to its position. If so then my answer should work.
You should not use the clear method since that removes and deletes the animation, instead use takeAnimation(0) until there are no animations, and just add the new animations, but that logic should not be inside "Rad" but in the Test class:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class Rad(QtWidgets.QWidget):
def __init__(self, text, parent=None):
super(Rad, self).__init__(parent)
self.resize(50, 50)
self.radio = QtWidgets.QRadioButton()
self.label = QtWidgets.QLabel()
self.label.setText(text)
lay = QtWidgets.QVBoxLayout(self)
lay.addWidget(self.radio)
lay.addWidget(self.label)
self.animation = QtCore.QVariantAnimation()
self.animation.setDuration(1000)
self.animation.valueChanged.connect(self.on_value_changed)
self.animation.setStartValue(100)
self.animation.setEndValue(0)
#QtCore.pyqtSlot("QVariant")
def on_value_changed(self, val):
pos = self.pos()
pos.setY(val)
self.move(pos)
def swap_values(self):
self.animation.blockSignals(True)
start_value = self.animation.startValue()
end_value = self.animation.endValue()
self.animation.setStartValue(end_value)
self.animation.setEndValue(start_value)
self.animation.blockSignals(False)
class Test(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.buts = QtWidgets.QButtonGroup(self, exclusive=True)
wid_1 = Rad("but-200", self)
wid_1.setStyleSheet("background:brown;")
wid_1.move(200, 0)
wid_2 = Rad("but-100", self)
wid_2.setStyleSheet("background:yellow;")
wid_2.move(100, 0)
wid_3 = Rad("but-0", self)
wid_3.setStyleSheet("background:green;")
wid_3.move(0, 0)
self.buts.addButton(wid_1.radio, 0)
self.buts.addButton(wid_2.radio, 1)
self.buts.addButton(wid_3.radio, 2)
self.buts.buttonToggled.connect(self.on_button_toggled)
self.group = QtCore.QSequentialAnimationGroup(self)
self.last_widget = None
#QtCore.pyqtSlot(QtWidgets.QAbstractButton, bool)
def on_button_toggled(self, button, state):
if state:
wid = button.parent()
if self.group.animationCount() > 0:
self.group.takeAnimation(0)
if isinstance(self.last_widget, Rad):
self.last_widget.swap_values()
self.group.addAnimation(self.last_widget.animation)
wid.swap_values()
self.group.addAnimation(wid.animation)
self.group.start()
self.last_widget = wid
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Test()
w.resize(500, 500)
w.show()
sys.exit(app.exec_())

Passing data from a QThread to another QThread

I have a situation where a Gui is active and a QThread.
The QThread is getting and saving data in the background all the time, it should not stop doing this.
Now I want to process the latest data from the QThread without interrupting the QThread or freezing the Gui.
So I think I need another thread to do this?!
How can I pass its data to another thread and do something with it?
import sys, random, time
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
self.setWindowTitle('Window')
#getData
self.myGetData = getData()
self.myGetData.start()
self.show()
class getData(QThread):
#This Thread should run all the time
def run(self):
while True:
myNumber = random.randint(0, 100)
#He 'processData Thread'!! Do Something with mynumber!!
time.sleep(1)
class processData(QThread):
def processNumber(self, myNumber):
#Extremly complex code will execute while 'getData' is doing its thing.
newNumber = myNumber * 10
return newNumber
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())
Found a lot of examples on how to pass data from a QThread to the interface (signals).. But not the other way around.
The signals are confusing me a bit in this case..
I would like to propose do next:
import sys, random, time
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
from PyQt5 import Qt #+
class getData(QThread):
#This Thread should run all the time
threadSignalGetData = pyqtSignal(int)
def __init__(self, myNumber):
super().__init__()
self.myNumber = myNumber
def run(self):
#myNumber = 0
while True:
#He 'processData Thread'!! Do Something with mynumber!!
Qt.QThread.msleep(1000)
self.myNumber += 1
self.threadSignalGetData.emit(self.myNumber)
class MsgBoxGetData(Qt.QDialog):
def __init__(self):
super().__init__()
layout = Qt.QVBoxLayout(self)
self.label = Qt.QLabel("")
layout.addWidget(self.label)
close_btn = Qt.QPushButton("Close window GetData")
layout.addWidget(close_btn)
close_btn.clicked.connect(self.close)
self.setGeometry(900, 65, 400, 80)
self.setWindowTitle('MsgBox GetData')
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: green;
font-size: 16px;}""")
class processData(QThread):
threadSignalProcessData = pyqtSignal(int, int)
def __init__(self, myNumber):
super().__init__()
self.newNumber = myNumber
def run(self):
flagProcessData = True
while flagProcessData:
#Extremly complex code will execute while 'getData' is doing its thing.
newNumber = self.newNumber * 10
self.threadSignalProcessData.emit(self.newNumber, newNumber)
flagProcessData = False
class MsgBoxProcessData(Qt.QDialog):
def __init__(self):
super().__init__()
layout = Qt.QVBoxLayout(self)
self.label = Qt.QLabel("")
layout.addWidget(self.label)
close_btn = Qt.QPushButton("Close window ProcessData")
layout.addWidget(close_btn)
close_btn.clicked.connect(self.close)
self.setGeometry(900, 200, 400, 80)
self.setWindowTitle('MsgBox ProcessData')
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: red;
font-size: 24px;}""")
class Ui(Qt.QWidget):
def __init__(self, parent=None):
super(Ui, self).__init__(parent)
layout = Qt.QVBoxLayout(self)
self.lbl = Qt.QLabel("process GUI")
layout.addWidget(self.lbl)
self.btnA = Qt.QPushButton("Start getData")
layout.addWidget(self.btnA)
self.btnB = Qt.QPushButton("Start processData")
layout.addWidget(self.btnB)
self.setGeometry(550, 65, 300, 300)
self.setWindowTitle('Window')
self.btnA.clicked.connect(self.usingGetData)
self.btnB.clicked.connect(self.usingProcessData)
self.myNumber = 0
self.newNumber = None
self.msgGetData = MsgBoxGetData()
self.threadGetData = None
self.msgProcessData = MsgBoxProcessData()
self.threadProcessData = None
self.counter = 0
self.timer = Qt.QTimer()
self.timer.setInterval(1000)
# -------- timeout -------> def recurring_timer(self):
self.timer.timeout.connect(self.recurring_timer)
self.timer.start()
self.setStyleSheet("""QLabel{
font-family:'Consolas';
color: blue;
font-size: 20px;}""")
self.show()
def recurring_timer(self):
self.counter += 1
self.lbl.setText("process GUI: %d" % self.counter)
# ---- getData(QThread) -----------------------------------------------------#
def usingGetData(self):
if self.threadGetData is None:
self.threadGetData = getData(self.myNumber)
self.threadGetData.threadSignalGetData.connect(self.on_threadSignalGetData)
self.threadGetData.finished.connect(self.finishedGetData)
self.threadGetData.start()
self.btnA.setText("Stop getData(QThread)")
else:
self.threadGetData.terminate()
self.threadGetData = None
self.btnA.setText("Start getData(QThread)")
def finishedGetData(self):
self.threadGetData = None
self.btnA.setText("Start getData(QThread)")
def on_threadSignalGetData(self, value):
self.myNumber = value
self.msgGetData.label.setText(str(self.myNumber))
if not self.msgGetData.isVisible():
self.msgGetData.show()
# --END-- getData(QThread) -------------------#
# ---- processData(QThread) -----------------------------------------------------#
def usingProcessData(self):
if self.threadProcessData is None:
self.threadProcessData = processData(self.myNumber)
self.threadProcessData.threadSignalProcessData.connect(self.on_threadSignalProcessData)
self.threadProcessData.finished.connect(self.finishedProcessData)
self.threadProcessData.start()
self.btnB.setText("Stop processData(QThread)")
else:
self.threadProcessData.terminate()
self.threadProcessData = None
self.btnB.setText("Start processData(QThread)")
def finishedProcessData(self):
self.threadProcessData = None
self.btnB.setText("Start processData(QThread)")
def on_threadSignalProcessData(self, value1, value2):
self.newNumber = value2
self.msgProcessData.label.setText(str(value1)+" * 10 = "+str(self.newNumber))
if not self.msgProcessData.isVisible():
self.msgProcessData.show()
# --END-- processData(QThread) -------------------#
# -------------------- closeEvent --------------------------------------- #
def closeEvent(self, event):
reply = Qt.QMessageBox.question\
(self, 'Question',
"QUIT ?",
Qt.QMessageBox.Yes,
Qt.QMessageBox.No)
if reply == Qt.QMessageBox.Yes:
# close getData(QThread)
if self.threadGetData:
self.threadGetData.terminate()
self.msgGetData.close()
# close processData(QThread)
if self.threadProcessData:
self.threadProcessData.terminate()
self.msgProcessData.close()
#event.accept()
super().closeEvent(event)
else:
event.ignore()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Ui()
sys.exit(app.exec_())

Get GUI element value from QThread

How can a QThread get text from a QLineEdit?
i tried self.t.updateSignal.connect(self.inputedittext.text) to get the QLineEdit value, but I get an error:
TypeError: unsupported operand type(s) for +=:
PyQt4.QtCore.pyqtBoundSignal' and 'int'
or I get the message:
bound signal updateSignal of xxxxxx at 0x02624580
Code:
import sys
import time
from PyQt4 import QtGui, QtCore
class mc(QtGui.QWidget):
def __init__(self):
super(mc,self).__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('QThread')
self.inputedittext = QtGui.QLineEdit()
self.startbutton = QtGui.QPushButton('start')
self.stopbutton = QtGui.QPushButton('stop')
self.textlable = QtGui.QLabel('0')
lv1 = QtGui.QVBoxLayout()
lb1 = QtGui.QHBoxLayout()
lb1.addWidget(self.inputedittext)
lb1.addWidget(self.startbutton)
lb1.addWidget(self.stopbutton)
lb2 = QtGui.QHBoxLayout()
lb2.addWidget(self.textlable)
lv1.addLayout(lb1)
lv1.addLayout(lb2)
self.setLayout(lv1)
self.t = test_QThread()
self.t.updateSignal.connect(self.inputedittext.text)
self.startbutton.clicked.connect(self.start_t)
self.connect(self.t,QtCore.SIGNAL('ri'),self.setlable)
def setlable(self,i):
self.textlable.setText(i)
def start_t(self):
self.t.start()
# print(self.inputedittext.text())
class test_QThread(QtCore.QThread):
updateSignal = QtCore.pyqtSignal(QtCore.QString)
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
i = self.updateSignal
# i=0
go = True
while go:
i+=1
time.sleep(1)
self.emit(QtCore.SIGNAL('ri'),str(i))
print('run...')
def main():
app = QtGui.QApplication(sys.argv)
mw = mc()
mw.show()
app.exec_()
if __name__ == '__main__':
main()
Use signals to communicate from thread to gui, and from gui to thread:
class mc(QtGui.QWidget):
...
def initUI(self):
...
self.t = test_QThread()
self.t.progressSignal.connect(self.setlable)
self.t.requestSignal.connect(self.sendText)
self.startbutton.clicked.connect(self.start_t)
self.stopbutton.clicked.connect(self.stop_t)
def sendText(self):
self.t.updateSignal.emit(self.inputedittext.text())
def setlable(self, i):
self.textlable.setText(str(i))
def start_t(self):
self.t.start()
def stop_t(self):
self.t.stop()
class test_QThread(QtCore.QThread):
requestSignal = QtCore.pyqtSignal()
updateSignal = QtCore.pyqtSignal(str)
progressSignal = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(test_QThread, self).__init__(parent)
self.updateSignal.connect(self.updateSlot)
self._running = False
self._count = 0
def updateSlot(self, text):
print 'received: "%s", count: %d' % (text, self._count)
def stop(self):
self._running = False
def run(self):
self._count = 0
self._running = True
while self._running:
self._count += 1
time.sleep(1)
self.progressSignal.emit(self._count)
if self._count % 3 == 0:
self.requestSignal.emit()

Categories