i want to create QLabels dynamically at runtime, and change the Text afterwards. I did it like that:
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.counter = 0
self.items = self.read_hosts()
self.layout = QGridLayout()
for item in self.items:
self.item = QLabel(item, self)
self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.item.setAlignment(Qt.AlignCenter)
self.item.setStyleSheet("QLabel {background-color: green;}")
self.layout.addWidget(self.item,self.counter, 0)
self.counter += 1
self.setLayout(self.layout)
self.startWorker()
self.show()
def change_txt(self, lb, i):
self.item.setText("{}".format(i))
It won't work. I understand why it would change just the text of the last label. I'm doing something wrong during assignment.
How can I create all labels completely variably and subsequently change the texts?
I am using:
PyQT5 on Windows 10
Thanks!
Here is my whole code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import os
class Worker(QObject):
update = pyqtSignal(str,int)
exception = pyqtSignal(str)
def read_hosts(self):
#try:
file = open("hosts.ini", "r")
return file.readlines()
#except Exception as ex:
#self.exception.emit(str(ex))
def check_ping(self):
#try:
hosts = self.read_hosts()
while True:
for host in hosts:
print(host)
params = " -l 1000"
response = os.system("ping " + host + params)
print("weiter")
self.update.emit(host, response)
#except Exception as ex:
#self.exception.emit(str(ex))
class Window(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.counter = 0
self.items = self.read_hosts()
self.layout = QGridLayout()
for item in self.items:
self.item = QLabel(item, self)
self.item.setObjectName("label" + str(self.counter))
print("label" + str(self.counter))
self.item.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.item.setAlignment(Qt.AlignCenter)
self.item.setStyleSheet("QLabel {background-color: green;}")
self.layout.addWidget(self.item,self.counter, 0)
self.counter += 1
self.setLayout(self.layout)
self.startWorker()
self.show()
def startWorker(self):
self.thread = QThread()
self.obj = Worker()
self.thread = QThread()
self.obj.moveToThread(self.thread)
self.obj.update.connect(self.onUpdate)
self.obj.exception.connect(self.onException)
self.thread.started.connect(self.obj.check_ping)
self.thread.start()
def read_hosts(self):
#try:
file = open("hosts.ini", "r")
return file.readlines()
#except Exception as ex:
#self.exception.emit(str(ex))
def onException(self, msg):
QMessageBox.warning(self, "Eine Exception im Worker wurde geworfen: ", msg)
def onUpdate(self, lb, i):
label = lb
self.label0.setText("{}".format(i))
app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())
hosts.ini:
192.168.1.1
192.168.1.2
192.168.1.30