qml中调取数据库中的数据显示在SwitchDelegate控件中
时间: 2023-12-10 14:41:53 浏览: 163
如果你使用的是Qt的Sql模块连接数据库,可以通过以下步骤在QML中调用数据库中的数据并显示在SwitchDelegate控件中:
1. 在C++中创建一个继承自QAbstractListModel的模型类,重写rowCount()、data()等方法,用于从数据库中获取数据并在QML中显示。
```cpp
class SwitchModel : public QAbstractListModel
{
Q_OBJECT
public:
// 构造函数和析构函数
// ...
// 重写方法
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
private:
QSqlDatabase m_db;
};
```
2. 在rowCount()方法中返回数据库中数据的行数。
```cpp
int SwitchModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
QSqlQuery query(m_db);
query.exec("SELECT COUNT(*) FROM switches");
if (query.next()) {
return query.value(0).toInt();
}
return 0;
}
```
3. 在data()方法中返回指定行和列的数据,根据role参数决定返回什么类型的数据。
```cpp
QVariant SwitchModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() < 0 || index.row() >= rowCount())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole) {
QSqlQuery query(m_db);
query.prepare("SELECT name, status FROM switches LIMIT 1 OFFSET :row");
query.bindValue(":row", index.row());
if (query.exec() && query.next()) {
if (query.columnCount() == 2) {
if (query.value(1).toBool()) {
return QVariant(QStringLiteral("On"));
} else {
return QVariant(QStringLiteral("Off"));
}
}
}
}
return QVariant();
}
```
4. 在QML文件中使用ListView控件显示数据,并设置SwitchDelegate控件用于显示开关状态。
```qml
ListView {
width: 200
height: 200
model: switchModel
delegate: SwitchDelegate {
text: model.name
checked: model.status === "On"
}
}
```
注意:需要在C++中将SwitchModel类注册为一个可在QML中使用的类型,可以使用qmlRegisterType()函数实现。
完整的代码可以参考以下示例:
```cpp
#include <QAbstractListModel>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
class SwitchModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit SwitchModel(QObject *parent = nullptr)
: QAbstractListModel(parent)
, m_db(QSqlDatabase::addDatabase("QSQLITE"))
{
m_db.setDatabaseName("switches.db");
if (!m_db.open()) {
qWarning() << "Failed to open database:" << m_db.lastError().text();
}
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override
{
Q_UNUSED(parent)
QSqlQuery query(m_db);
query.exec("SELECT COUNT(*) FROM switches");
if (query.next()) {
return query.value(0).toInt();
}
return 0;
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
{
if (!index.isValid())
return QVariant();
if (index.row() < 0 || index.row() >= rowCount())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole) {
QSqlQuery query(m_db);
query.prepare("SELECT name, status FROM switches LIMIT 1 OFFSET :row");
query.bindValue(":row", index.row());
if (query.exec() && query.next()) {
if (query.columnCount() == 2) {
if (query.value(1).toBool()) {
return QVariant(QStringLiteral("On"));
} else {
return QVariant(QStringLiteral("Off"));
}
}
}
}
return QVariant();
}
private:
QSqlDatabase m_db;
};
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
SwitchModel switchModel;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("switchModel", &switchModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
#include <QAbstractButton>
#include <QCheckBox>
#include <QPainter>
#include <QStyleOption>
class SwitchDelegate : public QAbstractButton
{
Q_OBJECT
public:
explicit SwitchDelegate(QWidget *parent = nullptr)
: QAbstractButton(parent)
, m_checked(false)
{}
QSize sizeHint() const override
{
return QSize(60, 30);
}
bool isChecked() const override
{
return m_checked;
}
void setChecked(bool checked) override
{
if (m_checked != checked) {
m_checked = checked;
emit toggled(m_checked);
update();
}
}
protected:
void paintEvent(QPaintEvent *event) override
{
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QBrush bgBrush(m_checked ? QColor("#4CD964") : QColor("#B2B2B2"));
painter.setBrush(bgBrush);
painter.setPen(Qt::NoPen);
painter.drawRoundedRect(rect(), 15, 15);
QBrush fgBrush(m_checked ? QColor("#FFFFFF") : QColor("#FFFFFF"));
painter.setBrush(fgBrush);
QRectF fgRect = QRectF(0, 0, width()/2, height());
if (m_checked) {
fgRect.translate(width()/2, 0);
}
painter.drawEllipse(fgRect);
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
setChecked(!m_checked);
}
}
private:
bool m_checked;
};
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
SwitchModel switchModel;
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData(R"qml(
import QtQuick 2.15
import QtQuick.Controls 2.15
ListView {
width: 200
height: 200
model: switchModel
delegate: SwitchDelegate {
text: model.name
checked: model.status === "On"
}
}
)qml", QUrl());
QObject *rootObject = component.create();
return app.exec();
}
#include <QQmlEngine>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
SwitchModel switchModel;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("switchModel", &switchModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
```
阅读全文