Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Using Tree Model to Store Data?



  • Currently:
    I have created and populated a QTreeWidget with QTreeWidgetItems, and have set the text of the QTreeWidgetItems

    Problem: I have no idea how to actually utilize the QTreeWidgetItems for data storage
    Looking at: https://doc.qt.io/qt-5/qt.html#ItemDataRole-enum

    void QTreeWidgetItem::setData(int column, int role, const QVariant &value)
    

    I see that I can use a Qt::ItemDataRole to specify the type of data stored, but none of the options in the enumeration pertain to actually storing raw data, only Qt properties.

    Questions:

    • How would I store actual data, such as doubles, within a WTreeWidgetItem?

    • If I am not supposed to actually store data within the tree items, do I need to use an auxilary structure and use model indexes with internal pointers to link the 2 together?

    Info:

    • Qt5 (c++)

    • MSVC 2017 + Qt Designer[link text](link url)


  • Lifetime Qt Champion

    @AlexanderAlexander said in Using Tree Model to Store Data?:

    How would I store actual data, such as doubles, within a WTreeWidgetItem?

    You can store whatever you want in the QVariant.



  • @AlexanderAlexander said in Using Tree Model to Store Data?:

    I can use a Qt::ItemDataRole to specify the type of data stored

    No. the Qt::ItemDataRole is just a "hint" about what you are storing. the type of data is completely determined by the variant. In all Qt native models Qt::DisplayRole and Qt::EditRole are exactly the same

    I have no idea how to actually utilize the QTreeWidgetItems for data storage

    Examples:

    • Set the text of the item in the first column: item->setData(0,Qt::DisplayRole,QStringLiteral("Hello"));
    • Set a numerical value as displayed in the first column: item->setData(0,Qt::DisplayRole,3.14);
    • Set the text colour for the the item in the first column: item->setData(0,Qt::ForegroundRole,QBrush(Qt::red));
    • Store a value that your program will use later: item->setData(0,Qt::UserRole,5);
    • Store another value that your program will use later: item->setData(0,Qt::UserRole+1,35);

Log in to reply