josef.van.niekerk
josef.van.niekerk

Reputation: 12121

Qt passing QString to struct constructor doesn't work

I've got the following struct :

struct HidItem
{
    HidItem(){}
    HidItem(QString commandName, uint commandValue)
    {
        name = commandName;
        value = commandValue;
    }

    QString name;
    uint value;
};

and trying to create an instance like so:

HidCommandModel::HidCommandModel()
    : QAbstractListModel(),
      hidData(new QVector<HidItem>(10))
{
    HidItem *hidItem = new HidItem("USAGE_PAGE", 1);
    hidData->append(*(hidItem));
}

This isn't working too well, as only the uint commandValue gets assigned to the HidItem instance, and not the QString "USAGE_PAGE"

I haven't coded C++ in quite a few years, but this seems to me that I'm passing the string incorrectly, and needs to have some kung fu involved with pass by reference, pointers and copy and write.

The theory is there, but my practical skills are letting me down horribly today. Can anyone assist?

Upvotes: 0

Views: 2672

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

Works for me:

struct HidItem
{
    HidItem(){}
    HidItem(QString commandName, uint commandValue)
    {
        name = commandName;
        value = commandValue;
    }

    QString name;
    uint value;
};


int main(int argc, char ** argv) {
    QApplication app( argc, argv );

    HidItem *hidItem = new HidItem("USAGE_PAGE", 1);
    qDebug() << hidItem->name << "," << hidItem->value;
}

Output:

"USAGE_PAGE" , 1

One thing you should change is the signature of the HidItem constructor, so that it expects a const reference instead of an object:

HidItem(const QString& commandName, uint commandValue) {
...

This avoids unnecessary creation of temporary objects. But still, your approach also works well.


The real issue is the wrong usage of the QVector constructor:

QVector<HidItem>* hidData = new QVector<HidItem>(10);
hidData->append(hidItem);

appends the hidItem as element #11, since the QVector already contains 10 elements after being created.

Simply use

QVector<HidItem>* hidData = new QVector<HidItem>();
hidData->append(hidItem);

(and consider the remarks regarding new by @Mike Seymour).

Upvotes: 3

Related Questions