DEV Community

海前 王
海前 王

Posted on

QT MODEL AND VIEW


CPP
#if 0
#include <QApplication>
#include <QListView>
#include <QStandardItemModel>
#include <QDebug>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 创建 QListView 和 QStandardItemModel
    QListView* listView = new QListView;
    QStandardItemModel* model = new QStandardItemModel(listView);

    // 为 QListView 设置数据模型
    listView->setModel(model);

    // 使用 setItem() 函数添加列表项
    QStandardItem* item1 = new QStandardItem("Item 1");
    model->setItem(0, 0, item1);

    QStandardItem* item2 = new QStandardItem("Item 2");
    model->setItem(0, 1, item2);//not found

    QStandardItem* item3 = new QStandardItem("Item 3");
    model->setItem(2, 0, item3);

    // 显示 QListView
    listView->show();

    return app.exec();
}
#endif
#if 0
#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>
#include <QDebug>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 创建 QTableView 和 QStandardItemModel

    QTableView* tableView = new QTableView;
    QStandardItemModel* model = new QStandardItemModel(0, 3, tableView);
    QStandardItemModel* model2 = new QStandardItemModel(1, 13, tableView);
    // 设置模型到 QTableView

    tableView->setModel(model);

    // 添加几行数据
    model->appendRow(new QStandardItem("Row 1, Col 1"));
    model->appendRow(new QStandardItem("Row 2, Col 1"));
    model->appendRow(new QStandardItem("Row 3, Col 1"));
    tableView->setModel(model2);

    // 添加几行数据
    model2->appendRow(new QStandardItem("Row 1, Col 1"));
    model2->appendRow(new QStandardItem("Row 2, Col 1"));
    model2->appendRow(new QStandardItem("Row 3, Col 1"));

    QStnadradItem* item= model->invisibleRootItem();

    QList<QStandardItem*> li;
    li.append(new QStandardItem("Row 1, Col 2"));
    li.append(new QStandardItem("Row 2, Col 2"));
    li.append(new QStandardItem("Row 3, Col 2"));
    model2->insertColumn(1, li);

    // 设置列宽
    tableView->setColumnWidth(0, 150);
    tableView->setColumnWidth(1, 150);
    tableView->setColumnWidth(2, 150);

    // 显示 QTableView
    tableView->show();

    return app.exec();
}




#include <QApplication>
#include <QStandardItemModel>
#include <QTableView>
#include <QVBoxLayout>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 创建主窗口
    QWidget window;
    QVBoxLayout* layout = new QVBoxLayout(&window);

    // 创建表格视图
    QTableView* tableView = new QTableView;
    layout->addWidget(tableView);

    // 创建数据模型
    QStandardItemModel* model = new QStandardItemModel;
    tableView->setModel(model);

    // 添加一些数据
    QStandardItem* item;
    item = new QStandardItem("Row 1, Col 1");
    model->invisibleRootItem()->setChild(0, 0, item);
    item = new QStandardItem("Row 1, Col 2");
    model->invisibleRootItem()->setChild(0, 1, item);
    item = new QStandardItem("Row 2, Col 1");
    model->invisibleRootItem()->setChild(1, 0, item);
    item = new QStandardItem("Row 2, Col 2");
    model->invisibleRootItem()->setChild(1, 1, item);

    // 在第1列插入一个新的项目
       QStandardItem* newItem = new QStandardItem("New Column");
    model->invisibleRootItem()->appendColumn( QList<QStandardItem*>() << newItem);


    // 设置表头
    model->setHeaderData(0, Qt::Horizontal, "Column 1");
    model->setHeaderData(1, Qt::Horizontal, "Column 2");

    // 显示窗口
    window.show();
    return app.exec();
}

#include <QApplication>
#include <QMainWindow>
#include <QStandardItemModel>
#include <QTreeView>
#include <QVBoxLayout>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 创建主窗口
    QMainWindow mainWindow;

    // 创建 QTreeView 和 QStandardItemModel
    QTreeView* treeView = new QTreeView(&mainWindow);
    QStandardItemModel* model = new QStandardItemModel(&mainWindow);

    // 设置列头
    model->setHorizontalHeaderLabels(QStringList() << QStringLiteral("序号") << QStringLiteral("名称"));

    // 初始化树形结构
    for (int i = 0; i < 5; i++)
    {
        // 一级节点
        QStandardItem* item1 = new QStandardItem(QString::number(i));
        QStandardItem* item2 = new QStandardItem(QStringLiteral("一级节点"));
        model->setItem(i, 0, item1);
        model->setItem(i, 1, item2);

        for (int j = 0; j < 5; j++)
        {
            // 二级节点
            QStandardItem* item3 = new QStandardItem(QString::number(j));
            QStandardItem* item4 = new QStandardItem(QStringLiteral("二级节点"));
            item1->setChild(j, 0, item3);
            item1->setChild(j, 1, item4);

            for (int k = 0; k < 5; k++)
            {
                // 三级节点
                QStandardItem* item5 = new QStandardItem(QString::number(k));
                QStandardItem* item6 = new QStandardItem(QStringLiteral("三级节点"));
                item3->setChild(k, 0, item5);
                item3->setChild(k, 1, item6);
            }
        }
    }

    // 给 QTreeView 应用 model
    treeView->setModel(model);

    // 布局
    QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(treeView);
    QWidget* centralWidget = new QWidget(&mainWindow);
    centralWidget->setLayout(layout);
    mainWindow.setCentralWidget(centralWidget);

    mainWindow.show();
    return a.exec();
}
#endif

#if 0
#include<QDebug>
#include <QApplication>
#include <QMainWindow>
#include <QStandardItemModel>
#include <QTreeView>
#include <QVBoxLayout>
#include <QIcon>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 创建主窗口
    QMainWindow mainWindow;

    // 创建 QTreeView 和 QStandardItemModel
    QTreeView* treeView = new QTreeView(&mainWindow);
    QStandardItemModel* model = new QStandardItemModel(&mainWindow);

    treeView->setIconSize(QSize(32, 32));
    // 设置列头
    model->setHorizontalHeaderLabels(QStringList() << QStringLiteral("序号") << QStringLiteral("名称"));

    // 初始化树形结构
    for (int i = 0; i < 5; i++)
    {
        // 一级节点
        QStandardItem* item1 = new QStandardItem(QString::number(i));
        QStandardItem* item2 = new QStandardItem(QStringLiteral("一级节点"));
        item2->setIcon(QIcon("C:/Qt/Qt5.3.1/Tools/QtCreator/bin/untitled8/icon.png")); // 设置节点图标
        model->setItem(i, 0, item1);
        model->setItem(i, 1, item2);

        for (int j = 0; j < 5; j++)
        {
            // 二级节点
            QStandardItem* item3 = new QStandardItem(QString::number(j));
            QStandardItem* item4 = new QStandardItem(QStringLiteral("二级节点"));
            item4->setIcon(QIcon("C:/Qt/Qt5.3.1/Tools/QtCreator/bin/untitled8/icon.png")); // 设置节点图标
            item3->setIcon(QIcon("C:/Qt/Qt5.3.1/Tools/QtCreator/bin/untitled8/icon.png")); // 设置节点图标
            item1->setChild(j, 0, item3);
            item1->setChild(j, 1, item4);

            for (int k = 0; k < 5; k++)
            {
                // 三级节点
                QStandardItem* item5 = new QStandardItem(QString::number(k));
                QStandardItem* item6 = new QStandardItem(QStringLiteral("三级节点"));
                item6->setIcon(QIcon("C:/Qt/Qt5.3.1/Tools/QtCreator/bin/untitled8/icon.png")); // 设置节点图标
                item3->setChild(k, 0, item5);
                item3->setChild(k, 1, item6);

            }
        }
    }


    // 给 QTreeView 应用 model
    treeView->setModel(model);
    QModelIndex m= model->index(4,1);
    qDebug()<<m;

    qDebug() << "Rows:" << model->rowCount() << "Columns:" << model->columnCount();

    // 布局
    QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(treeView);
    QWidget* centralWidget = new QWidget(&mainWindow);
    centralWidget->setLayout(layout);
    mainWindow.setCentralWidget(centralWidget);

    mainWindow.show();
    return a.exec();
}





#include <QApplication>
#include <QDataWidgetMapper>
#include <QStandardItemModel>
#include <QLineEdit>
#include <QSpinBox>
#include <QComboBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
#include<QSqlTableModel>
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // 创建数据模型
    QStandardItemModel *model = new QStandardItemModel(3, 3, nullptr);
    model->setHeaderData(0, Qt::Horizontal, "Name");
    model->setHeaderData(1, Qt::Horizontal, "Age");
    model->setHeaderData(2, Qt::Horizontal, "Gender");

    // 填充数据模型
    model->setData(model->index(0, 0), "John");
    model->setData(model->index(0, 1), 25);
    model->setData(model->index(0, 2), "Male");
    model->setData(model->index(1, 0), "Jane");
    model->setData(model->index(1, 1), 30);
    model->setData(model->index(1, 2), "Female");
    model->setData(model->index(2, 0), "Bob");
    model->setData(model->index(2, 1), 35);
    model->setData(model->index(2, 2), "Male");

    // 创建小部件
    QLineEdit *nameEdit = new QLineEdit;
    QSpinBox *ageSpinBox = new QSpinBox;
    QComboBox *genderComboBox = new QComboBox;
    genderComboBox->addItems({"Male", "Female"});
    QPushButton *prevButton = new QPushButton("Previous");
    QPushButton *nextButton = new QPushButton("Next");

    // 创建 QDataWidgetMapper 并设置数据模型
    QDataWidgetMapper *mapper = new QDataWidgetMapper(nullptr);
    mapper->setModel(model);

    // 添加映射关系
    mapper->addMapping(nameEdit, 0);
    mapper->addMapping(ageSpinBox, 1);
    mapper->addMapping(genderComboBox, 2);

    // 设置当前索引并显示数据
    mapper->toFirst();

    // 创建布局并添加小部件
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(nameEdit);
    layout->addWidget(ageSpinBox);
    layout->addWidget(genderComboBox);
    layout->addWidget(prevButton);
    layout->addWidget(nextButton);

    QWidget window;
    window.setLayout(layout);
    window.show();

    // 连接信号和槽
    QObject::connect(prevButton, &QPushButton::clicked, mapper, &QDataWidgetMapper::toPrevious);
    QObject::connect(nextButton, &QPushButton::clicked, mapper, &QDataWidgetMapper::toNext);

    return app.exec();
}

#endif
#include <QApplication>
#include <QTableView>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlQueryModel>
#include <QDebug>

bool createConnection() {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("example.db");

    if (!db.open()) {
        qDebug() << "Error: Unable to connect to database.";
        return false;
    }

    QSqlQuery query;

    // Clear existing tables
    query.exec("DROP TABLE IF EXISTS users");
    query.exec("DROP TABLE IF EXISTS profiles");
    query.exec("DROP TABLE IF EXISTS orders");
    query.exec("DROP TABLE IF EXISTS products");
    query.exec("DROP TABLE IF EXISTS order_products");

    // Create tables
    query.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
    query.exec("CREATE TABLE profiles (id INTEGER PRIMARY KEY, user_id INTEGER, bio TEXT, FOREIGN KEY(user_id) REFERENCES users(id))");
    query.exec("CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, product TEXT, FOREIGN KEY(user_id) REFERENCES users(id))");
    query.exec("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT)");
    query.exec("CREATE TABLE order_products (order_id INTEGER, product_id INTEGER, FOREIGN KEY(order_id) REFERENCES orders(id), FOREIGN KEY(product_id) REFERENCES products(id))");

    // Insert sample data
    query.exec("INSERT INTO users (name) VALUES ('Alice')");
    query.exec("INSERT INTO users (name) VALUES ('Bob')");
    query.exec("INSERT INTO profiles (user_id, bio) VALUES (1, 'Loves programming')");
    query.exec("INSERT INTO profiles (user_id, bio) VALUES (2, 'Enjoys hiking')");
    query.exec("INSERT INTO orders (user_id, product) VALUES (1, 'Laptop')");
    query.exec("INSERT INTO orders (user_id, product) VALUES (2, 'Smartphone')");
    query.exec("INSERT INTO products (name) VALUES ('Laptop')");
    query.exec("INSERT INTO products (name) VALUES ('Smartphone')");
    query.exec("INSERT INTO order_products (order_id, product_id) VALUES (1, 1)");
    query.exec("INSERT INTO order_products (order_id, product_id) VALUES (2, 2)");

    return true;
}

void showQueryResult(const QString &queryStr) {
    QSqlQueryModel *model = new QSqlQueryModel;
    model->setQuery(queryStr);
    if (model->lastError().isValid()) {
        qDebug() << model->lastError();
        return;
    }

    QTableView *view = new QTableView;
    view->setModel(model);
    view->show();
}

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    if (!createConnection())
        return -1;

    // One-to-One: Users and Profiles
    showQueryResult("SELECT users.name, profiles.bio FROM users JOIN profiles ON users.id = profiles.user_id");

    // One-to-Many: Users and Orders
    showQueryResult("SELECT users.name, orders.product FROM users JOIN orders ON users.id = orders.user_id");

    // Many-to-Many: Orders and Products
    showQueryResult("SELECT orders.product, products.name FROM orders JOIN order_products ON orders.id = order_products.order_id JOIN products ON products.id = order_products.product_id");

    return app.exec();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)