开发者

how to send QList<Object *> objects to another class?

i'm trying to send a QList as a parameter to another class but for some reason i lose all it's content ... (when i open the object with the debuger i see for objects...)

trying to send QList books to class Print:

class Store: public QWidget {
    Q_OBJECT
public:
    Analyze(QWidget *parent = 0);
    void generate_report();
    ~Analyze();

private:
    QList<Book *> books;

};

class Print
{
public:
    Print(开发者_StackOverflow社区);
    bool generate_report_file(QList<Book *> *);
};

i'm sending books like this:

void Analyze::generate_report()
{
.
.
.

    Print p;
    if (!p.generate_report_file(&books))
        QMessageBox::warning(this, "XML Escape","Error creating out.html", QMessageBox::Ok);
}


Small example

#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QList>
#include <QString>

void print_list(QList<QString *> * k)
{
    for (int i=0; i<k->size(); i++)
    {
        qDebug() << *k->at(i);
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QList<QString *> books;
    books.append(new QString("asd"));
    books.append(new QString("asdfgh"));
    books.append(new QString("asdjhhhhhhtyut"));
    print_list (&books);

    return a.exec();
}

so just use * in function when calling elements of your QList, like in qDebug() << *k->at(i); string


You should pass the QList by value. The reason, while this may seem silly on the surface, is that QList is implicitly shared. Please read http://doc.trolltech.com/latest/implicit-sharing.html to see more on that topic.


#include <QtCore/QtCore>

void
printList(const QStringList& list)
{
    foreach (const QString& str, list) {
        qDebug() << str;
    }
}

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

    QStringList list;
    list << "A" << "B" << "C";

    printList(list);

    return QCoreApplication::exec();
}

There is already a class called QStringList to use. Also, you would want to pass it by reference. Also, you do not want to use pointers on containers or QString. As they are automatically implicitly shared. So it's bad design to use pointers on those two.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜