Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QHBoxLayout delete QPushButton



  • Delete QPushButton in QHBoxLayout fail.

    QHBoxLayout *hbox = new QHBoxLayout;
    
    void windowAdded(WId wid){
        Dock *dock = new Dock;
        dock->wid = wid;
        QPushButton *pushButton = new QPushButton(icon, NULL);
        pushButton->setUserData(DOCK, dock);
        hbox->addWidget(pushButton);
    }
    
    void windowRemoved(WId wid){
        for (int i=0; i<hbox->count();i++) {
            QLayoutItem *LI = hbox->layout()->itemAt((i));
            QPushButton *pushButton = qobject_cast<QPushButton*>(LI->widget());
            Dock *dock = (Dock*)(pushButton->userData(DOCK));
            if (dock->wid == wid) {
                delete LI;
            }
        }
    }
    

  • Lifetime Qt Champion

    Hi
    The layout owns it so
    you must use
    https://doc.qt.io/qt-5/qlayout.html#takeAt

    and delete that. ( will also delete its widget as far as i remembers )



  • I have to disagree with mrjj. It is true that the layout owns the push button. However, IIRC the push button also knows its parent and will delete itself from it when deleted. So, at least in theory your code should work.

    Nevertheless, I am not sure if you correctly use setUserData/userData. I have never encountered it and the reason for this is that it is not part of the public API. So, the best advice is: Don't use it! Quick googling gave me this: https://stackoverflow.com/questions/8260763/about-using-an-undocumented-class-in-qt Their advice is to use QObject::setProperty instead. You are more likely to get help in this forum if you use only documented features.



  • @SimonSchroeder Strange solved by these:
    A layout in a big layout. delete cause overlap.
    Change to:
    A QWidget with the layout in a big layout, delete work fine.

    QList<QPushButton *> list_pushButton = widget_app->findChildren<QPushButton *>();    //QWidget
    for (int i=0; i<list_pushButton.count(); i++) {
        Dock *dock = (Dock*)(list_pushButton.at(i)->userData(DOCK));
                if (dock->wid == wid) {
                    hbox_app->removeWidget(list_pushButton.at(i));    // QHBoxLayout in QWidget
                    list_pushButton.at(i)->deleteLater();
                }
    }
    

Log in to reply