Important: Please read the Qt Code of Conduct -

Memory management with QListWidget

  • I create a new item with new QListWidgetItem and then I give it to the list with tree_widget->addItem(pItem) but the clang static analyser says it's a potential memory leak. Is there a right way to establish the QObject relationship here so it's not a problem?

  • @Vadi2
    if tree_widget is a QListWidget, then this code will not result in memory leak:

    QListWidget wgt;
    QListWidgetItem *item = new QListWidgetItem("myitem");

    The list widget will take ownership of the item. Also my clang analyzer sees no problem in this snippet.

  • Eh. Mine does for some reason:

    Memory Error: Memory leak: Potential leak of memory pointed to by 'pItem'
     1: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1150
     2: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     3: Looping back to the head of the loop in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     4: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     5: Looping back to the head of the loop in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     6: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     7: Looping back to the head of the loop in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     8: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1205
     9: Looping back to the head of the loop in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1150
    10: Entering loop body in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1150
    11: Memory is allocated in /home/vadi/Programs/Mudlet/mudlet/src/dlgConnectionProfiles.cpp:1156

    This is the line in question.

  • @Vadi2 Hi, friend. Welcome.

    Form your github.

    /** begin for loop*/
    auto pItem = new QListWidgetItem(;
    if (/** some conditions */) {
                // delete pItem; ///< so, you should delete pItem, before continue
                continue; ///< if continue at here, your pItem will make member leak.
    /** some code */
    profiles_tree_widget->addItem(pItem); ///< at here you add item to tree widget
    /** end for loop*/

  • You're right! Thank you.

Log in to reply