Home > other >  create widget in python automatic
create widget in python automatic

Time:01-10

I want send a newly and dynamically created widget directly into a specifique container QWidget by clicking on QPushButton. I tried some things but to no avail, it doesnt work.

def __init__(self):
        QMainWindow.__init__(self)
        self.resize(600, 500)
        self.wd = wd= QWidget(self)
        
        wd.resize(300,150)
        wd.move(10, 100) 

        bt = QPushButton('Create a button', self)
        bt.clicked.connect(self.creat_textLabel)
        bt.resize(100,30)
        bt.move(0, 0)        
    
    def creat_textLabel(self):
        lbl = QLabel('user new', self)
        lbl.move(0, 0)
        lbl.show

CodePudding user response:

(1) - I added some imports
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize   
(2) - Added this also, create the and call the main class of your app...
class MainWindow(QMainWindow):

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )
(3) - i repositioned your contenair, so that it doesn't mixing with the new label to be created in position (move(0,0))
wd.move(10, 100)
(4) - I added some colors to help in identifying widgets...
wd.setStyleSheet('background:red;')
lbl.setStyleSheet('background:blue; color:white;')
(5) - The key point is here
lbl = QLabel('user new', self) #doing this create & positionne QLabel in self == myApp

lbl = QLabel('user new', self.wd)  #I suggest this

Finally, below ==> The full fixed working code!

#!/usr/bin/env python
#coding: utf-8

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize   

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(600, 500)
        self.wd = wd= QWidget(self)
        wd.setStyleSheet('background:red;')
        wd.resize(300,150)
        wd.move(10, 100) 
        
        bt = QPushButton('Create a button', self)
        bt.clicked.connect(self.creat_textLabel)
        bt.resize(100,30)
        bt.move(100, 250)        
    
    def creat_textLabel(self):
        lbl = QLabel('user new', self.wd)
        lbl.setStyleSheet('background:blue; color:white;')
        lbl.move(0, 0)
        lbl.show()
        
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

enter image description here

And I would suggest you change the Posting TITLE to something like:

Pyqt5: hosting a dynamically created QWidget (QLabe) into a specific Container (QWidget)

  •  Tags:  
  • Related