Search code examples
c++qt6

How to remove `fromStdVector` method from Qt 6.3.0 c++ code


With Qt 6.3.0 QVector no longer has fromStdVector method. I didn't fully understand the answers in copying a std::vector to a qvector and would like to know how to modify the TreeWidgetController::getReponses method below.

In particular these templates were suggested:

std::vector<T> stdVec;
QVector<T> qVec = QVector<T>(stdVec.begin(), stdVec.end());

foreach is referenced Qt foreach loop ordering vs. for loop for QList and here https://doc-snapshots.qt.io/qt6-dev/foreach-keyword.html

The area I am unclear about is: ResponsePtr could replace T but how would the new ResponseItem be handled?

// This is a sample of the code, I would like to upgrade
void TreeWidgetController::getResponses()
{
    // First remove all possible previous children.
    removeAllChildren(_rootResponses);
    // Retrieve the list of available responses.
    vector<ResponsePtr> responses = dbSubsystem().getResponses();
    // Create a new ResponseItem for every response.
    foreach (ResponsePtr r, QVector<ResponsePtr>::fromStdVector(responses))
        new ResponseItem(_rootResponses, r);
}

Solution

  • There's no need to re-invent the wheel here, just have a look at the fromStdVector() method that is in qcorelib/tools/qvector.h in earlier versions of Qt:

    static inline QVector<T> fromStdVector(const std::vector<T> &vector)
    {
       return QVector<T>(vector.begin(), vector.end());
    }
    

    You can either include that function verbatim in one of your own headers and leave your code unchanged, or use it as an example of how you can modify your code.