c 部分的代码:
代码语言:javascript复制#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtQml>
...
#include "bookmodel.h"
int main(int argc, char *argv[])
{
...
qmlRegisterType<BookModel>("Backend", 1, 0, "BookModel");//向qml注册类型
BookModel *bookModel = new BookModel();//这是自己定义的类
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel();
...
bookModel->read(io->text()["book"]);//io是自己定义的读取json的类
QQmlApplicationEngine *engine = new QQmlApplicationEngine();
proxyModel->setSourceModel(bookModel);
//向qml传递变量
engine->rootContext()->setContextProperty("bookModel", bookModel);
engine->rootContext()->setContextProperty("proxyModel", proxyModel);
engine->load(QUrl(QLatin1String("qrc:/main.qml")));
return app.exec();
}
qml部分的代码: Search是自己写的一个搜索框
代码语言:javascript复制import QtQuick 2.7
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.1
import QtQuick.Controls.Universal 2.1
import QtQuick.Window 2.1
import Backend 1.0
LDialog{//LDialog是自己修改过的的对话框Dialog
title: "查找"
width: 460
height: 180
signal search(int range, string text)
Row{
spacing: 20
ComboBox{
id: combo
model:[qsTr("书名"),qsTr("出版社"),qsTr("作者"),qsTr("简介"),qsTr("购书日期"),qsTr("id"),qsTr("ISBN号"),qsTr("价格")]
}
TextField {
id: word
width: 200
}
Button {
id: searchBtn
text: qsTr("查找")
onClicked: {
var comap=new Array(BookModel.NameRole,BookModel.PublishRole,BookModel.AuthorRole,
BookModel.BriefRole,BookModel.BuyTimeRole,BookModel.IdRole,
BookModel.IsbnRole,BookModel.PriceRole);//这里的Role是BookModel类里面的一个enum
search(comap[combo.currentIndex],word.text);
}
}
}
}
使用时:
代码语言:javascript复制 Search{
id: findBookDialog
onSearch: {
proxyModel.filterRole=range;//这个filterRole是proxyModel搜索的范围,也就是指定BookModel中的一个属性
proxyModel.setFilterFixedString(text);//设置搜索内容
bookView.model=proxyModel;//设置展示的内容为搜索筛选后的
}
onRejected: {//取消时显示原来的内容
bookView.model=bookModel;
}
}