clear QList method



  • i have a QList member of ClassA, what should i do if i want to clear this QList?
    (1)m_listA.clear()

    (2)QList<A*>().swap(m_listA)

    (3)for (QList<A>::iterator it = m_listA.begin(); it != m_listA.end(); it++)
    {
    A* a= it;
    if (a)
    {
    delete a;
    a = NULL;
    }
    }
    //clear
    if (!m_listA.isEmpty())
    QList<A
    >().swap(m_listA);

    which is the best and efficient way to do this , thank you!



  • Hi,

    You can use QList::clear() if you want to remove all the items from your list.
    If you want to remove only few specific contents you can use QList::remveAll(const T &value).
    And also there is a function qDeleteAll from which you can delete the contents of list



  • how about the pointer?
    i use QList<A*>
    should i write like this:
    for (QList<A*>::iterator it = m_listA.begin(); it != m_listA.end(); it++)
    {
    A* a= *it;
    if (a)
    {
    delete a;
    a = NULL;
    }
    }
    //clear
    if (!m_listA.isEmpty())
    m_listA.clear();


  • Lifetime Qt Champion

    Hi,

    qDeleteAll is perfectly suited for that


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.