下面是一个示例的QT代码,实现了用户选择模式后将其存入SQlite数据库表,并在智能灯界面显示数据库表的最新信息。

#include <QtWidgets>
#include <QtSql>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void onModeSelected();
    void onViewLatestInfo();

private:
    QSqlDatabase m_db;
    QPushButton *m_btnMode1;
    QPushButton *m_btnMode2;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    m_db.setDatabaseName("database.sqlite");
    if (!m_db.open()) {
        QMessageBox::critical(this, "Error", "Failed to open database");
        return;
    }

    QSqlQuery query;
    query.exec("CREATE TABLE IF NOT EXISTS modes (id INTEGER PRIMARY KEY, mode TEXT)");

    m_btnMode1 = new QPushButton("Mode 1", this);
    connect(m_btnMode1, &QPushButton::clicked, this, &MainWindow::onModeSelected);

    m_btnMode2 = new QPushButton("Mode 2", this);
    connect(m_btnMode2, &QPushButton::clicked, this, &MainWindow::onModeSelected);

    QPushButton *btnViewLatestInfo = new QPushButton("View Latest Info", this);
    connect(btnViewLatestInfo, &QPushButton::clicked, this, &MainWindow::onViewLatestInfo);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(m_btnMode1);
    layout->addWidget(m_btnMode2);
    layout->addWidget(btnViewLatestInfo);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}

MainWindow::~MainWindow()
{
    m_db.close();
}

void MainWindow::onModeSelected()
{
    QPushButton *btn = qobject_cast<QPushButton*>(sender());
    QString mode = btn->text();

    QSqlQuery query;
    query.prepare("INSERT INTO modes (mode) VALUES (:mode)");
    query.bindValue(":mode", mode);
    query.exec();

    QMessageBox::information(this, "Success", "Mode selected and saved to database");
}

void MainWindow::onViewLatestInfo()
{
    QSqlQuery query;
    query.exec("SELECT mode FROM modes ORDER BY id DESC LIMIT 1");
    if (query.next()) {
        QString mode = query.value(0).toString();
        QMessageBox::information(this, "Latest Info", "Latest mode selected: " + mode);
    } else {
        QMessageBox::information(this, "Latest Info", "No mode found in the database");
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

#include "main.moc"

代码中创建了一个名为modes的SQlite数据库表,用于存储用户选择的模式。onModeSelected()函数在用户选择模式后将其插入数据库表。onViewLatestInfo()函数从数据库表中获取最新的模式信息并在消息框中显示。

请注意,代码中使用了QSqlDatabase和QSqlQuery类来进行数据库操作,需要在.pro文件中添加QT += sql以启用数据库支持。另外,需要将数据库文件database.sqlite放置在代码所在的工作目录中。

希望对你有帮助

帮我写一个QT代码要求用户在主界面选择模式后存入SQlite数据库表点击智能灯界面可以显示数据库表的最新信息

原文地址: https://www.cveoy.top/t/topic/izRX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录