我在这里感到沮丧。我实现了自定义QSqlTableModel
,但我无法在QML文件中使用它。但它适用于我的C ++代码!
这是我到目前为止所做的:
#include <QSqlQuery>
#include <QSqlTableModel>
#include "tablemodel.h"
MyTableModel::MyTableModel() : QSqlTableModel()
{
setTable("Event");
setEditStrategy(QSqlTableModel::OnFieldChange);
select();
}
这是我的QML定义:
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.1
import org.qtproject.examples.calendar.tablemodel 1.0
Window {
visible:true
width: 640
height: 400
minimumWidth: 400
minimumHeight: 300
color: "#f4f4f4"
title: "Table example"
MyTableModel{
id : myModel
}
TableView{
model:myModel
anchors.fill: parent
}
}
这是主文件,注释代码可以工作,但我想从QML内部显示表。
#include <QtQml>
#include <QtGui>
#include <QTableView>
#include "qtquickcontrolsapplication.h"
#include "sqleventmodel.h"
#include "tablemodel.h"
#include "mytableview.h"
int main(int argc, char *argv[])
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test");
if (!db.open()) {
qFatal("Cannot open database");
}
QtQuickControlsApplication app(argc, argv);
qmlRegisterType<MyTableModel>("org.qtproject.examples.calendar.tablemodel", 1, 0, "MyTableModel");
QQmlApplicationEngine engine(QUrl("qrc:/qml/main.qml"));
return app.exec();
}