How can I display a QStringList in C++ to a QML ListView

拟墨画扇 提交于 2019-12-04 19:58:01

You are doing it wrong. In every possible way. You even name getContext() the function that actually sets the context.

m_resultList is never set to anything in that code you have provided. So there is no way to tell you why your application is crashing, because the actual data is a mystery.

You also have a QObject derived class - your SearchClass. So you should expose that as a context property, and then have the string list interfaced to QML by being implemented as a Q_PROPERTY of SearchClass.

Here is a simple example:

// the equivalent of your SearchClass
class Test : public QObject {
    Q_OBJECT
    Q_PROPERTY(QStringList model MEMBER m_model NOTIFY modelChanged)
    QStringList m_model;
  public slots:
    void setModel(QString m) {
      m_model = m.split(" ");
      modelChanged();
    }
  signals:
    void modelChanged();
};

// in main.cpp
  Test t;
  engine.rootContext()->setContextProperty("Test", &t);

// in main.qml
Column {
    TextField {
      onTextChanged: Test.setModel(text)
    }
    ListView {
      width: 200; height: 300
      spacing: 5    
      model: Test.model
      delegate: Rectangle {
        height: 25
        width: 200
        color: "lightgray"
        Text { text: modelData; anchors.centerIn: parent }
      }
    }
  }

As you type the text string is sent to Test::setModel(), which then splits it into space separated tokens and sets the QStringList, which is used as a model source for the list view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!