0

I want to add QWidgets like a QLabel to QGroupBox dynamically. And the layout of the groupbox should not be set for absolute positioning(I don't want a layout). If a QWidget is added to QGroupBox before adding the Qgroupbox to MainWindow layout, It works and It is shown on the window. When I try to add a QWidget like Qlabel dynamically as it is shown in the addWidget function, It does not show the widget. Am I missing a point?

 class DropableGroupBox(QtWidgets.QGroupBox):
    def __init__(self,*args):
        super().__init__(*args)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()

    def dropEvent(self, event):
        pos = event.pos()
        text = event.mimeData().text()
        event.acceptProposedAction()


class ResultWindow(DropableGroupBox):
    def __init__(self,*args):
        super().__init__(*args)
        self.groupBox  = QtWidgets.QGroupBox()
        self.groupBox.setStyleSheet("background-color:yellow;")
        #labelx = DraggableLabel("Label", self.groupBox)

        vLay = QtWidgets.QVBoxLayout()
        vLay.addWidget(self.groupBox)
        self.setLayout(vLay)

    def dropEvent(self, event):
        text = event.mimeData().text()
        Curpos =self.mapFromGlobal(QtGui.QCursor().pos()) 
        self.addWidget(text,Curpos)
        event.acceptProposedAction()

    def addWidget(self,text,pos):
        if text=="label":
            labelx = DraggableLabel("Label",self)
            labelx.move(50,50)
            labelx.setStyleSheet("background-color:red")
            print("Here is")

1 Answers1

0

You are missing two important things:

  • if you want to add a child widget without using a layout manager, the parent must be set (possibly in the constructor), otherwise it will be considered top level widgets and it will be shown with its own window;
  • if a widget is not added to a layout manager, it has to be explicitly shown if it has no parent, or if the parent has been already shown (like in your case);
    def addWidget(self,text,pos):
        if text=="label":
            labelx = DraggableLabel("Label", self)
            labelx.move(50,50)
            labelx.setStyleSheet("background-color:red")
            labelx.show()
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • I am sorry , actually there was the "self " word in here => labelx = DraggableLabel("Label", self). When I add "labelx.show()" it worked. Thank you ... – MUSAB AKICI Dec 11 '20 at 15:28