PDA

View Full Version : Delete last item in QListWidget, application crash....!



radory
21st July 2010, 03:47
Hi all,
i'm new to QT, I get application crashed when i delete the last item in QListWidget....
following is my code...



#include <QtGui>

class MainWindow : public QWidget
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0)
: QWidget(parent)
{
_listWidget = new QListWidget(this);
_listWidget->resize(300,200);
_textEdit = new QTextEdit(this);
_textEdit->move(0,240);

for(int i= 0 ; i < 3 ; i++){
QListWidgetItem *item = new QListWidgetItem(_listWidget);
item->setData(Qt::DisplayRole, tr("item %1").arg(i));
item->setData(Qt::DecorationRole, qApp->style()->standardIcon(QStyle::SP_DirIcon));
}

connect(_listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWi dgetItem*)),
this, SLOT(listItemChged(QListWidgetItem*,QListWidgetIte m*)));

QPushButton *delBtn = new QPushButton(tr("Delete current item"), this);
delBtn->move(0, 210);
connect(delBtn, SIGNAL(clicked()), this, SLOT(delCurrItem()));

resize(600,700);
}


private slots:
void listItemChged(QListWidgetItem* currItem, QListWidgetItem*)
{
_textEdit->append(currItem->data(Qt::DisplayRole).toString());
}

void delCurrItem()
{
if(_listWidget->count() < 1) return;
delete _listWidget->currentItem();
}

private:
QListWidget *_listWidget;
QTextEdit *_textEdit;

};

#include "main.moc"

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}

Could somebody help me? thanks in advance....
Sorry for my poor English....

saa7_go
21st July 2010, 04:31
When you delete the last item, in this function



void listItemChged(QListWidgetItem* currItem, QListWidgetItem*)
{
_textEdit->append(currItem->data(Qt::DisplayRole).toString());
}


currItem points to null (0). So, you need to check currItem value before accessing it.



if(currItem != 0)
_textEdit->append(currItem->data(Qt::DisplayRole).toString());

radory
21st July 2010, 06:16
When you delete the last item, in this function



void listItemChged(QListWidgetItem* currItem, QListWidgetItem*)
{
_textEdit->append(currItem->data(Qt::DisplayRole).toString());
}




currItem points to null (0). So, you need to check currItem value before accessing it.



if(currItem != 0)
_textEdit->append(currItem->data(Qt::DisplayRole).toString());


It's works now ....
Thanks a lot....

aamer4yu
21st July 2010, 07:40
Would suggest to use -
delete QListWidget::takeItem(index);

instead of delete QListWidget::currentItem;
You are simply deleting that item, without removing it from the list widget. So list widget is bound to hold an invalid pointer !

Also would advise to use QListWidget::itemActivated instead of currentItemChanged. Since itemActivated will be called only when user presses the item, and thats what you want I guess :rolleyes: