Since I am new in PyQt I am trying to solve a problem with dynamically change color of table cell - help is more than welcome.
Function testFunction should change tableWidget color if for loop find 1 in array or 0. Is it possible to set this properties? Box should automatically change color on every 2 seconds without any additional action. Check the code below...
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()
You must change realLayout.addWidget(tableWidget)
to realLayout.addWidget(self.tableWidget)
and and you should not use "sleep", must create a timer(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()