Qt C ++返回字符串值

时间:2015-09-24 19:42:22

标签: c++ qt qml

我有以下代码:

filter.h

#pragma once

#include <QObject>
#include <QSortFilterProxyModel>

class FilterModel : public QSortFilterProxyModel
{
    Q_OBJECT

public:
    explicit FilterModel(QObject *parent = 0);

    Q_INVOKABLE QString getText (QString text);
};

filter.cpp

#include "filter.h"
#include <QDebug>    

FilterModel::FilterModel(QObject *parent) : QSortFilterProxyModel(parent) {}

QString FilterModel::getText(QString text)
{
    QString qmltext = text;
    qmltext != NULL ? qDebug() << qmltext
                    : qDebug() << "TEXT = NULL";

    return qmltext;
}

的main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "abonentstable.h"
#include "filter.h"

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

    QQmlApplicationEngine engine;

    AbonentsSqlModel *abonentsSqlModel = new AbonentsSqlModel;
    abonentsSqlModel->setQuery("SELECT * FROM abonents");

    FilterModel *filterModel = new FilterModel;
    filterModel->setSourceModel(abonentsSqlModel);

    filterModel->setFilterKeyColumn(0);
    filterModel->setFilterWildcard("9");

    QQmlContext *context = engine.rootContext();
    context->setContextProperty("abonents", filterModel);
    context->setContextProperty("filter", filterModel);

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

    return app.exec();
}

.qml文件部分:

TextField {
    id: textField
...
    onTextChanged: {
        filter.getText(textField.text)
    }
...
}

方法getText()从QML TextField获取文本(突然!)并将其打印到调试器中,它工作正常。但正如您所看到的,我有表格排序的代码。 以下问题是:现在排序掩码是&#34; 9&#34;,它有效,但我需要以某种方式从QString qmltext返回getText()并将其放入filterModel->setFilterWildcard() in这样main.cpp

QString qmlText = filterModel.getText(QString);
...
filterModel->setFilterWildcard(qmlText);

当然,这仅仅是一个例子,它不起作用,我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我不完全明白你想做什么,但我认为你需要这样的东西(如果你真的需要返回值):

QString FilterModel::getText(const QString& text)
{
setFilterWildcard(text);
return text;
}

顺便说一下:

 qmltext != NULL

无效。改为使用:

qmltext.isEmpty() == false