如何在C ++中将QStringList显示到QML ListView [英] How can I display a QStringList in C++ to a QML ListView

查看:218
本文介绍了如何在C ++中将QStringList显示到QML ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是Qt的新手,我想提高自己的C ++技能,所以我决定启动一个项目,在其中可以使用文本字段在QStringList中搜索项目.我使搜索功能正常工作,并且能够将搜索结果移到另一个QStringList中,在其中可以使用它在声明为公共插槽"的函数中向用户显示.

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. 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".

主要思想是,一旦用户在文本字段中输入了一个字符,该列表就会自动更新.因此,我设法将结果列表放入Slot函数中,以便每次在文本字段中键入字符时都能显示不同的列表.

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.

在传递搜索结果列表的功能中,我正在尝试使用此功能

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));

其中resultModel是我在QML中的模型名称,而m_resultList是存储搜索结果的位置,以在ListView中显示列表.我的程序可以编译,但是运行后会崩溃.

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. My program compiles but it crashes after I run it.

所以,我的真正问题是:有什么方法可以将不在main.cpp中的C ++ QStringList显示到QML ListView中?

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中使用硬编码为QStringList的同一行,并且该列表能够显示,因此一定不是主要问题.同样是因为我无法使用SearchClass中的插槽功能来自动更新.

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. Also because I would not be able to use the slot function in SearchClass to auto update.

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

#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

#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

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
            }
        }
    }

}

推荐答案

您做错了.百般.您甚至可以为getContext()实际设置上下文的函数命名.

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

m_resultList从未设置为任何值.因此,由于实际数据是个谜,所以无法告诉您应用程序崩溃的原因.

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.

您还有一个QObject派生类-您的SearchClass.因此,您应该将其公开为上下文属性,然后通过将其实现为SearchClassQ_PROPERTY来将字符串列表连接到QML.

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.

这是一个简单的例子:

// 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 }
      }
    }
  }

键入时,文本字符串将发送到Test::setModel(),然后将其拆分为以空格分隔的标记,并设置QStringList,用作列表视图的模型源.

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.

这篇关于如何在C ++中将QStringList显示到QML ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆