由于我是PyQt的新手,我试图通过动态改变表格单元格的颜色来解决问题 - 非常欢迎帮助。
函数 testFunction 应该更改tableWidget颜色,如果 for loop 在数组中找到1或0.是否可以设置此属性? Box应该每2秒自动更改颜色,无需任何其他操作。检查下面的代码......
import sys, os
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setWindowTitle("Hello!")
self.tableWidget = QtGui.QTableWidget()
self.tableItem = QtGui.QTableWidgetItem()
self.tableWidget.resize(400,250)
self.tableWidget.setRowCount(1)
self.tableWidget.setColumnCount(1)
self.tableWidget.setItem(0,0, QtGui.QTableWidgetItem("START TOOL"))
self.tableWidget.item(0,0).setBackground(QtGui.QColor(100,100,150))
realLayout = QtGui.QVBoxLayout()
realLayout.addWidget(tableWidget)
self.setLayout(realLayout)
self.testFunction()
def testFunction(self) :
a = [1,0,1,1,1,1,1,0,0,0,0,0,1]
for i in range(0,len(a)) :
if a[i] == 1 :
self.tableWidget.item(0,0).setBackground(QtGui.QColor(100,100,100))
else :
self.tableWidget.item(0,0).setBackground(QtGui.QColor(0,255,0))
time.sleep(2)
def main():
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
GUI.show()
sys.exit(app.exec_())
if __name__ == '__main__' :
main()
答案 0 :(得分:0)
您必须将realLayout.addWidget(tableWidget)
更改为realLayout.addWidget(self.tableWidget)
并且您不应使用“睡眠”,必须创建计时器(QTimer
)
import sys, os
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QTimer
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setWindowTitle("Hello!")
self.tableWidget = QtGui.QTableWidget()
self.tableItem = QtGui.QTableWidgetItem()
self.tableWidget.resize(400, 250)
self.tableWidget.setRowCount(1)
self.tableWidget.setColumnCount(1)
self.tableWidget.setItem(0, 0, QtGui.QTableWidgetItem("START TOOL"))
self.tableWidget.item(0, 0).setBackground(QtGui.QColor(100, 100, 150))
realLayout = QtGui.QVBoxLayout()
realLayout.addWidget(self.tableWidget)
self.setLayout(realLayout)
self.counter = 0
self.a = [1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1]
self.testFunction()
timer = QTimer(self)
timer.timeout.connect(self.testFunction)
timer.start(2*1000)
def testFunction(self):
self.counter += 1
self.counter %= len(self.a)
if self.a[self.counter]:
self.tableWidget.item(0, 0).setBackground(QtGui.QColor(100, 100, 100))
else:
self.tableWidget.item(0, 0).setBackground(QtGui.QColor(0, 255, 0))
def main():
app = QtGui.QApplication(sys.argv)
GUI = MainWindow()
GUI.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()