我正在尝试更新qlcdnumber的值。我想做的就是在单独的线程中运行一个函数,该函数输出一个值(在这种情况下,仅计数向上)并将此值显示在屏幕上。
这是我正在使用的python脚本,在下面是.UI文件的内容(其中qlcdnumber命名为" disp"):
import sys
import threading
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import uic
from time import sleep
Ui_MainWindow, QtBaseClass = uic.loadUiType("./disp.ui")
class MainWindow(QMainWindow, Ui_MainWindow):
counter = pyqtSignal(int)
counting = False
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.disp.display(?????) #<----
def startCounting(self):
if not self.counting:
self.counting = True
thread = threading.Thread(target=self.something)
thread.start()
def something(self):
for i in range(100):
self.counter.emit(int(i))
sleep(0.5)
self.counting = False
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
.ui文件:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>577</width>
<height>504</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QLCDNumber" name="disp"/>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>577</width>
<height>24</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
您几乎在那里,您正在发出带有新值的信号,但是您的信号未连接到任何函数,您只需要创建一个函数即可更新qlcdnumber的值并连接您对此功能的信号反面:
import sys
import threading
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import uic
from time import sleep
Ui_MainWindow, QtBaseClass = uic.loadUiType("./disp.ui")
class MainWindow(QMainWindow, Ui_MainWindow):
counter = pyqtSignal(int)
counting = False
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.counter.connect(self.update_lcd)
# self.startCounting()
def update_lcd(self, value):
self.disp.display(value)
def startCounting(self):
if not self.counting:
self.counting = True
thread = threading.Thread(target=self.something)
thread.start()
def something(self):
for i in range(100):
self.counter.emit(int(i))
sleep(0.5)
self.counting = False
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
我建议使用Qthread或Qrunnable而不是线程模块来启动您的背景任务。可以在此处找到对差异的很好的解释。