Aug-26-2019, 03:24 AM
I need to be able to dynamically add an object like a label to my window. How do I do that? Here is the code that I have.
import random import sys from PIL import Image from PyQt5 import QtCore, QtWidgets from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication, QWidget from Image2 import Ui_Form class MyMainWindow(QWidget, Ui_Form): human_list = [] def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.setupUi(self) self.addHuman(random.randint(1, 10000), random.randint(1, 500), random.randint(1, 200)) def mouseDoubleClickEvent(self, event): self.addHuman(random.randint(1, 10000), random.randint(1, 500), random.randint(1, 200)) def addHuman(self, humanId, x, y): human = HumanLabel(humanId, x, y, self) human.addHumanLabel() self.human_list.append(human) QApplication.processEvents() class HumanLabel(): def __init__(self, humanId, x, y, Form): self.humanId = humanId self.x = x self.y = y self.form = Form def addHumanLabel(self): self.label = QtWidgets.QLabel(self.form) self.label.setGeometry(QtCore.QRect(self.x, self.y, 500, 375)) img = Image.open('./321.jpg') img.resize((20, 20), Image.ANTIALIAS) self.label.setPixmap(QPixmap('./456.jpg')) self.label.setObjectName(str(self.humanId)) if __name__ == '__main__': app = QApplication(sys.argv) win = MyMainWindow() win.show() sys.exit(app.exec_())
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import QPixmap class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(500, 375) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(0, 0, 500, 375)) self.label.setPixmap(QPixmap('./123.jpg')) self.label.setObjectName("background") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form"))The problem is when I double click the mouse that the new human label is being created but it will not show on the window. How do I get the label to show on the window?