PDA

View Full Version : Uses on Qvariant in the address book example



thefatladysingsopera
6th July 2011, 11:04
Hello,i am studying the address book example on Qt Assistant and on the address book example i have a come across usages of Qvariant which i don't understand.

Here is the code:


QVariant TableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();//what does the use of Qvariant here mean - 1

if (index.row() >= listOfPairs.size() || index.row() < 0)
return QVariant();//what does the use of Qvariant here mean - 2

if (role == Qt::DisplayRole) {
QPair<QString, QString> pair = listOfPairs.at(index.row());

if (index.column() == 0)
return pair.first;
else if (index.column() == 1)
return pair.second;
}
return QVariant();//what does the use of Qvariant here mean - 3
}

I have commented on the code next to Qvariant usages.Someone help me understand what it means.

mcosta
6th July 2011, 11:49
The default QVariant::QVariant() constructor creates an invalid object.

You can test for valid QVariant with code



QVariant obj = model->data(index, role);
if (obj.isValid()) {
// Do Something with valid data
}
else {
// Handle invalid data
}

thefatladysingsopera
6th July 2011, 12:06
I don't understand,could you explain in relation to the code i've given?.

Thanks.

mcosta
6th July 2011, 13:17
The code you posted check if there are the condition to return a "valid" result.
If don't it returs an invalid QVariant, in this way the caller may say if the result is valid.