#include <QApplication>
#include <QWidget>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QPainter>
#include <QMouseEvent>
class MyWidget : public QWidget {
Q_OBJECT
public:
MyWidget(QWidget *parent = nullptr) : QWidget(parent) {}
void mousePressEvent(QMouseEvent *event) override {
// 获取鼠标点击位置并将其保存到数据库
int x = event->x();
int y = event->y();
QSqlQuery query;
query.prepare("INSERT INTO points (x, y) VALUES (:x, :y)");
query.bindValue(":x", x);
query.bindValue(":y", y);
if (!query.exec()) {
qDebug() << "Error saving point to database: " << query.lastError();
}
}
void paintEvent(QPaintEvent *event) override {
// 从数据库中获取点并绘制到窗口
QPainter painter(this);
painter.setPen(Qt::blue);
QSqlQuery query;
query.exec("SELECT x, y FROM points");
while (query.next()) {
int x = query.value(0).toInt();
int y = query.value(1).toInt();
painter.drawPoint(x, y);
}
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
// 初始化数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("points.db");
if (!db.open()) {
qDebug() << "Error opening database: " << db.lastError();
return -1;
}
QSqlQuery query;
query.exec("CREATE TABLE IF NOT EXISTS points (x INTEGER, y INTEGER)");
MyWidget widget;
widget.resize(640, 480);
widget.setWindowTitle("Drawing with Database");
widget.show();
return app.exec();
}
这段代码演示了如何在Qt中结合数据库和绘图功能。当鼠标在窗口中点击时,点的坐标被保存到SQLite数据库中。在窗口重绘事件中,先前保存的点从数据库中检索并绘制到窗口上。这个例子简单地展示了如何将数据库操作和绘图功能整合到一个应用程序中。