I have recently picked up Qt again, and started refreshing my memory. Creating a custom data model for a table was easy enough.
Now I am trying to retrieve the selected data. Take note that I use custom data objects.
Example of my custom model:
platform.h
class Platform
{
public:
Platform();
Platform(QString name);
QString getName();
void setName(QString name);
private:
QString m_name;
};
Very simple data structure for testing purposes. I then implemented a QAbstractTableModel, the Data() method looks like this:
platformmodel.cpp
QVariant PlatformModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= m_platforms.size() || index.row() < 0)
return QVariant();
if (role == Qt::DisplayRole) {
Platform platform = m_platforms.at(index.row());
qDebug() << platform.getName();
return platform.getName();
}
return QVariant();
}
What I understand from this code is, that for the selectable items, a String is always returned, instead of a platform object.
For displaying, this works fine, I see the actual objects in the view. Now I want to select the actual object from the model, and not just a QString.
So the method body would be something like:
void MainWindow::selectionChangedSlot(const QItemSelection &, const QItemSelection &)
{
//get the text of the selected item
const QModelIndex index = ui->lvPlatforms->selectionModel()->currentIndex();
Platform selectedPlatform = index.data();//This returns a QVariant and will fail at compile time, but I want to achieve something along this line.
setWindowTitle(selectedPlatform.getName());
}
P.s. Maybe I am trying to search on the wrong thing, I can find examples that use custom objects, but none talk about retrieving the selected item.
There has to be a better way then retreiving the string, then looping trough the list of platforms and comparing the name to the selected item.. If i have a big list, having to loop trough each item and do string comparison is not very efficient.
I hope my problem is clear enough. If something important lacks, let me know so I can edit my example.
EDIT
I tried Q_DECLARE_METATYPE(Platform);
And yes it works, it makes it possible to store it in a QVariant, the problem is, since for displaying, a String is always expected, or 9/10 times anyway. So far it seems impossible to have both text display AND get the full platform object from the selection model(i can do both individually.. pretty useless..)