ورود

View Full Version : سوال: ارتباط با دیتابیس در QML



python_85
جمعه 25 بهمن 1392, 23:52 عصر
سلام
می خواستم با QML با دیتابیس کار کنم یه چند جا دیدم که باید از کلاس QSqlQueryModel یه کلاس به ارث ببرم ولی متاسفانه جواب نداد:

class SqlQueryModel: public QSqlQueryModel
{
Q_OBJECT
QHash<int,QByteArray> hash;
public:
explicit SqlQueryModel(QObject * parent) : QSqlQueryModel(parent)
{
//hash = new QHash<int,QByteArray>;
hash.insert(Qt::UserRole, QByteArray("id"));
hash.insert(Qt::UserRole + 1, QByteArray("text"));
this->setQuery("select id,text from [cat]");

//setRoleNames(roleNames);
}
QVariant data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);

}
else
{
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
qDebug((tr("").arg(value.toString()).toLatin1().data()));
return value;
}
QHash<int, QByteArray> roleNames() const{return hash;}
};


و تو main.cpp هم viewer.rootContext()->setContextProperty رو مقدار دادم
تو qml هم:

Rectangle {
opacity: 0
id:selectpoems
ListView {
id: listView1
anchors.fill: parent
model:List
delegate: Item {
id: delegate



anchors.margins: 4

Row {
anchors.margins: 4
anchors.fill: parent
spacing: 4;

Text {

text: text
width: 150
}

}
}
}
}



لطفا اگه کسی کار کرده کمک کنه
ممنون