2
我有QML TableView
和QSqlQueryModel
。我需要選擇任意行並從表格的每一列中獲取數據以分開TextField
。QML TableView從特定單元格中獲取數據(選定行+特定列)
這裏是abonentstable.h:
#pragma once
#include <QObject>
#include <QSqlQueryModel>
class AbonentsSqlModel : public QSqlQueryModel
{
Q_OBJECT
public:
explicit AbonentsSqlModel(QObject *parent = 0);
void setQuery(const QString &query, const QSqlDatabase &db = QSqlDatabase());
QVariant data(const QModelIndex &index, int role) const;
QHash<int, QByteArray> roleNames() const { return m_roleNames; }
private:
void generateRoleNames();
QHash<int, QByteArray> m_roleNames;
};
abonentstable.cpp:
#include "abonentstable.h"
#include <QSqlRecord>
#include <QSqlField>
AbonentsSqlModel::AbonentsSqlModel(QObject *parent) : QSqlQueryModel(parent)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("data_base.sqlite");
db.open();
}
void AbonentsSqlModel::setQuery(const QString &query, const QSqlDatabase &db)
{
QSqlQueryModel::setQuery(query, db);
generateRoleNames();
}
void AbonentsSqlModel::generateRoleNames()
{
m_roleNames.clear();
for(int i = 0; i < record().count(); i ++) {
m_roleNames.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
}
}
QVariant AbonentsSqlModel::data(const QModelIndex &index, int role) const
{
QVariant value;
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);
}
return value;
}
Table.qml:
TableView {
id: table
model: abonents
....
TableViewColumn {
delegate: Text {
text: " " + model.name + " " + model.surname
font.pointSize: 20
}
width: 575
}
TableViewColumn {
delegate: Text {
text: " " + model.phone
font.pointSize: 20
}
width: 575
}
TableViewColumn {
delegate: Text {
text: " " + model.ip_address
font.pointSize: 20
}
width: 525
}
}
和一些文字字段:
TextField {
id: leftText
}
TextField {
id: centerText
}
TextField {
id: rightText
}
這個sqlite表有4列,我需要從選定的行中獲取數據到這些文本字段:左2列,中心1和右1。