Python Forum
How to add a widget to a QtWindow after it has been created
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to add a widget to a QtWindow after it has been created
#4
In order to create the button on the fly and retain a copy of it you will have to attach it to something or it will simply get trashed (literally). Also while creating this button you need to retain a handle to the object so that you can reference the entire object as needed not something you usually do on the fly but still doable. So in your code
self.button = QtWidgets.QPushButton(self)
self.button is a reference to your QPushButton that you created and "self" means you have attached it to "window"
However here you do not attach the button to anything
b = QtWidgets.QPushButton(self)
which after its created pythons garbage collector picks it up and deletes it now
self.b = QtWidgets.QPushButton(self)
would attach it to your "window" and allow you to hold onto it then the question is what are you going to do with it, as it is very hard to manipulate this object as it is. However if you made the button a class of its own you could create various instances of it without issue and retain a handle to it. Then all you would have to do is store the data you need to recreate that button on the fly and re-create it from that data.
class ButTmplt(QPushButton)
    def __init__(self):
        QPushButton.__init__(self)
Note you could add extra parameters to this button if you needed them to define certain aspects that would be different from button to button such its name -- as follows:
class ButTmplt(QPushButton)
    def __init__(self, ButName):
        QPushButton.__init__(self)
        self.setText(ButName)
Oh and the reference line to create the button on the fly would be
    self.b = ButTmplt('ButtonName')
Oh and yes that only solves half your problem as now that you have an attached button how do you get it to show up -- well you would have to place it in the window somewhere but that greatly depends on how you have structured your window which you really did not supply so I cannot speak to that at all. Aka for future reference if you supply sufficient information (such as a minimal fully functional example code) then you might get full answers rather than just partial ones
Reply


Messages In This Thread
RE: How to add a widget to a QtWindow after it has been created - by Denni - Jul-12-2019, 08:05 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020