PDA

View Full Version : Error in changing the colour of the item of a listwidget



Ahmed Abdellatif
9th October 2017, 19:14
I am trying to do some operation of the selected item in a list widget if a pushbutton is clicked. this is done using the following code

void Dialog::on_pushButton_clicked()
{
if(MyListWidget->currentItem()->isSelected())
{
MyListWidget->currentItem()->setText("YOU");
QString my_text= MyListWidget->currentItem()->text();
qDebug()<<my_text;

MyListWidget->currentItem()->setBackgroundColor(Qt::green);
}
else return;
}

The program works well if we select an item before pressing the pushbutton,the problem occurs if no item is selected before clicking the button, the programme is crashed

admkrk
9th October 2017, 20:11
What happens if you just remove the else statement?

Ginsengelf
10th October 2017, 07:10
Hi, just guessing, but I think MyListWidget->currentItem() will return NULL.

A debugger will help you to determine the position and reason of the crash.

Ginsengelf

high_flyer
10th October 2017, 17:35
Try this:


void Dialog::on_pushButton_clicked()
{
QListWidgetItem *pCurrItem = MyListWidget->currentItem();
if(pCurrItem && pCurrItem->isSelected())
{
pCurrItem->setText("YOU");
QString my_text= pCurrItem->text();
qDebug()<<my_text;

pCurrItem->setBackgroundColor(Qt::green);
}
}