简体   繁体   English

如何在C ++中向QML ListView显示QStringList

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

So I'm new to Qt and I'm trying to improve my C++ skills, so I decided to start a project where I can search items in a QStringList using a textfield. 所以我是Qt的新手,我正在努力提高我的C ++技能,所以我决定开始一个项目,我可以使用文本字段在QStringList中搜索项目。 I got the search function working and I was able to move the result of the search into another QStringList , where I can use it to display to the user in a function that is declared as a "public slot". 我使搜索功能正常工作,我能够将搜索结果移动到另一个QStringList ,我可以使用它在一个声明为“公共插槽”的函数中向用户显示。

The main Idea is that the list will auto update as soon as the user enters a character into the textfield, which it already does. 主要的想法是,一旦用户将字符输入到文本字段中,该列表就会自动更新。 So I managed to get the resulted list into the Slot function to be able to display a different list every time and character gets typed in the textfield. 因此,我设法将结果列表放入Slot函数,以便每次都能显示不同的列表,并在文本字段中输入字符。


In the function where I pass in the list of search results, I am trying to use this 在我传递搜索结果列表的函数中,我试图使用它

m_context->setContextProperty("resultModel",QVariant::fromValue(m_resultList));

where resultModel is the name of my model in QML and m_resultList is where the results of the search are being stored, to display the list in the ListView . 其中resultModel是QML中我的模型的名称, m_resultList是存储搜索结果的位置,用于在ListView显示列表。 My program compiles but it crashes after I run it. 我的程序编译但运行后它崩溃了。

So, my true question is: Is there any way that I can display a C++ QStringList not in the main.cpp into a QML ListView? 所以,我的真正问题是:有没有办法可以将main.cpp中的C ++ QStringList显示到QML ListView中?

The reason why I'm asking for it to not be in the main is because I tried to use that same line above in the main.cpp with a hard coded QStringList and the list was able to display, so there must be an issue with it not being in the main. 我要求它不在主要部分的原因是因为我试图在main.cpp中使用上面的相同行,并使用硬编码的QStringList并且列表能够显示,因此必须存在问题它不是主要的。 Also because I would not be able to use the slot function in SearchClass to auto update. 另外因为我无法使用SearchClass的插槽功能来自动更新。


main.cpp main.cpp中

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
#include "searchclass.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<SearchClass>("b9c.backend", 1, 0, "BackEnd");

    QQmlApplicationEngine engine;

    SearchClass obj;

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    QQmlContext *context = engine.rootContext();

    obj.getContext(context);

    //the line below works if provided with a qstringlist

    //context->setContextProperty("resultModel", QVariant::fromValue(resultList));

    return app.exec();
}

SearchClass.h SearchClass.h

#ifndef SEARCHCLASS_H
#define SEARCHCLASS_H

#include <QObject>
#include <QQmlContext>

class SearchClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString userSearch READ userSearch WRITE setUserSearch NOTIFY userSearchChanged)

public:
    SearchClass(QObject *parent = 0);

    QStringList resultList;

    QString userSearch();
    void setUserSearch(QString &userSearch);

    void getFilenameAndInput(QString inputString);
    QString CompareInputAndFilename(QString inputString, QString filename);
    QStringList getFileName();

    //get context
    void getContext(QQmlContext *context);

signals:
    void userSearchChanged();

public slots:
    void setUserSearch();

private:
    QStringList m_resultList;
    QString m_userSearch;
    QQmlContext* m_context;
};

#endif // SEARCHCLASS_H

SearchClass.cpp SearchClass.cpp

#include "searchclass.h"
#include <QDebug>
#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>


SearchClass::SearchClass(QObject *parent) : QObject(parent)
{
    connect(this, SIGNAL(userSearchChanged()), this, SLOT(setUserSearch()));
}

//the result should be displayed in this SLOT when ever the user types in a character into the textfield
void SearchClass::setUserSearch(){

    qDebug() << "SLOT: " << m_resultList;

//The line below makes the program crash. It works when implemented in the main.cpp
//    m_context->setContextProperty("resultModel", QVariant::fromValue(m_resultList));

}

QString SearchClass::userSearch()
{
    return m_userSearch;
}

void SearchClass::setUserSearch(QString &userSearch)
{
    if (userSearch == m_userSearch)
        return;

    m_userSearch = userSearch;

    qDebug() << "Input: " <<m_userSearch;

    getFilenameAndInput(m_userSearch);

    emit userSearchChanged();
}

QStringList SearchClass::getFileName(){

//Returns the items that will be searched for...

}

void SearchClass::getFilenameAndInput(QString inputString){

//Puts the search results into class variable m_resultList...

    m_resultList = resultList;

}

QString SearchClass::CompareInputAndFilename(QString inputString, QString filename){

//Search processing... 

}

//gets context to use setProperty in the above signal, but it crashes
void SearchClass::getContext(QQmlContext *context){

    m_context = context;

}

main.qml main.qml

import QtQuick 2.6
import QtQuick.Controls 2.0
import b9c.backend 1.0
import QtQuick.Window 2.2


ApplicationWindow {
    id: root
    width: 300
    height: 480
    visible: true
    BackEnd { id: backend }

    TextField {
        id: txtfield
        text: backend.userSearch
        placeholderText: qsTr("Search...")
        width: parent.width

        onTextChanged: backend.userSearch = text
    }

    ListView {
        id:view
        height: parent.height
        width: parent.width
        y: 5 + txtfield.height
        model: resultModel

        delegate: Rectangle {
            border.color: "lightblue"
            height: 25
            width: parent.width
            Text {
                anchors.centerIn: parent
                text: modelData
            }
        }
    }

}

You are doing it wrong. 你做错了。 In every possible way. 百般。 You even name getContext() the function that actually sets the context. 您甚至将getContext()命名为实际设置上下文的函数。

m_resultList is never set to anything in that code you have provided. m_resultList永远不会设置为您提供的代码中的任何内容。 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 . 您还有一个QObject派生类 - 您的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 . 所以,你应该公开,作为一个上下文属性,再有通过被实现为接口,以QML字符串列表Q_PROPERTYSearchClass

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. 在您键入时,文本字符串将发送到Test::setModel() ,然后将其拆分为空格分隔的标记并设置QStringList ,该列表用作列表视图的模型源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM