【问题标题】:how to send QList<Object *> objects to another class?如何将 QList<Object *> 对象发送到另一个类?
【发布时间】:2010-07-05 12:00:05
【问题描述】:

我正在尝试将 QList 作为参数发送到另一个类,但由于某种原因我失去了它的所有内容...... (当我使用调试器打开对象时,我看到了对象...)

尝试将 QList 书籍发送到 Print 类:

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

private:
    QList<Book *> books;

};

class Print
{
public:
    Print();
    bool generate_report_file(QList<Book *> *);
};

我要寄这样的书:

void Analyze::generate_report()
{
.
.
.

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

【问题讨论】:

  • 显示 generate_report_file(QList *) 正文
  • bool Print::generate_report_file(QList *books) { //for each Book for (int i=0; isize(); i++) { }跨度>
  • 这个想法是打印每本书的属性...

标签: qt pointers qlist


【解决方案1】:

小例子

#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();
}

所以在调用 QList 的元素时只需在函数中使用 *,例如 qDebug() at(i);字符串

【讨论】:

    【解决方案2】:

    您应该按值传递 QList。原因虽然表面上看起来很傻,但 QList 是隐式共享的。请阅读 http://doc.trolltech.com/latest/implicit-sharing.html 以了解有关该主题的更多信息。

    【讨论】:

      【解决方案3】:
      #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();
      }
      

      已经有一个名为 QStringList 的类可供使用。此外,您可能希望通过引用传递它。此外,您不想在容器或 QString 上使用指针。因为它们是自动隐式共享的。所以在这两个上使用指针是不好的设计。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        相关资源
        最近更新 更多