# Qt6 开发知识点总结

### （1）Qt开发版本选择

在 Qt 6.5+ 系列中，**最稳定、兼容性最好**的版本是：

> **Qt 6.5.3**（当前公开最稳定的 Qt 6.5 LTS 补丁版本）

***

### （2）完整的开发环境：

Qt 6.5.3 + QML + CMake + MSVC 2019 + Qt Creator

***

### （3）获取当前时间戳

```
Component.onCompleted: {
        console.log(Qt.formatDateTime(new Date(),"yyyy-MM-dd HH:mm:ss.zzz"))
```

### ​（4）qml 实现日期时间的实时刷新显示

```
Item {
        Text { id: time }

        Timer {
            id:timer
            interval: 1000; running: true; repeat: true
            onTriggered: time.text = Qt.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss.zzz") 
        }

        Component.onCompleted: {
                    timer.start();
                }
```

### （5）QML中if else判断语句

```
import QtQuick

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Item {
        Text {
            id: time
            font.pixelSize: 24
        }

        Text {
            id: txtstatus
            x: 300
            font.pixelSize: 24
            text: qsTr("状态")
        }

        Timer {
            interval: 1000; running: true; repeat: true
            onTriggered: {

                time.text = Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")

                var d1 = '07:35:00'
                var d2 = '12:05:00'
                var d3 = '13:05:00'
                var d4 = '17:35:00'

                var d5 = Qt.formatDateTime(new Date(), "hh:mm:ss")
                console.log(d5)
                // console.log(typeof(d5))
                // console.log(typeof(d1))

                if ( d5===d1  || d5===d2 || d5===d3 || d5===d4 ){

                    txtstatus.text="正在插入..."
                    console.log("执行插入语句")
                }else{
                    txtstatus.text="等待执行插入中..."
                    console.log("等待状态！")
                }

            }

        }


    }


}



```

### （6）QML连接数据库

{% hint style="info" %}
参考资料：<https://by.cx/2018/08/qt-qml-mysql/>
{% endhint %}

### （7）用CMake设置应用程序图标

1. 先准备一张.ico的图标，命名为“appicon.ico”，放在与源文件同一级目录
2. 新建一个名称为“appicon.rc”的文件，键入一下内容： &#x20;

   ```js
   IDI_ICON1 ICON DISCARDABLE "appicon.ico"
   ```

   ![](https://3407761548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDFgj_K1oEIHPoXVkZG%2Fuploads%2FNP0QSqQZAK8PH7wnLwMz%2Fimage.png?alt=media\&token=4b628057-ea8d-4217-9fdf-3264916bc060)<br>
3. &#x20;在CMakeLists.txt文件中编辑以下内容：

   ```cmake
   set(APP_ICON_RESOURCE_WINDOWS "appicon.rc")
   qt_add_executable(appXSabre
       main.cpp
       ${APP_ICON_RESOURCE_WINDOWS}
   )                                        
   ```
4. 编译运行程序，可以看到窗口左上角和应用程序都已有了图标

{% hint style="info" %}
参考资料：<https://www.zigzagrainbow.com/blog/cmake-application-icon>

图标在线生成器：<http://icon.p2hp.com/>
{% endhint %}

（9）QML调用另一个QML文件并显示

**注意**&#x20;

1.调用的qml文件必须也是根元素为window，否则visible元素会报错。&#x20;

2.QML的文件第一个字母必须大写

3.要调用的QML文件必须在主QML里实例化    &#x20;

**main.qml文件**

```javascript
import QtQuick 2.12
import QtQuick.Window 2.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")


    Qml1{	//实例化另一个文件，文件名称第一个要大写
        id:qwe
    }


    Rectangle {
        width: 320; height: 240
        color: "black"

        Text {
            id: txt
            text: "打开另一个窗口"
            font.pixelSize: 20
            anchors.centerIn: parent
        }
        MouseArea {
            id: mouse_area
            anchors.fill: parent  // 有效区域
            onClicked: {
                qwe.show()	//另一个qml文件显示
            }
        }
    }
}

```

**Qml1.qml文件**

```
import QtQuick 2.0
import QtQuick.Window 2.2

Window {
    width: 320; height: 240
    visible: false	//该窗口一开始默认隐藏的
    color: "lightblue"
    
    Text {
        id: txt
        text: "另一个窗口"
        font.pixelSize: 20
        anchors.centerIn: parent
    }
}

```

{% hint style="info" %}
参考资料：<https://blog.csdn.net/youngdianfeng/article/details/107444117>
{% endhint %}

（9）QML调用C++

**方法1：**&#x5728;QML系统中注册C++类型

1.新建C++类，比如：sqlconnection，继承QObject类

![](https://3407761548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDFgj_K1oEIHPoXVkZG%2Fuploads%2FdKtZt1qZ2lxO98f7Gots%2Fimage.png?alt=media\&token=b98badfb-3fd9-4dd0-ac3a-77713cfbd641)

![](https://3407761548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDFgj_K1oEIHPoXVkZG%2Fuploads%2F6bTaEQ2ywkRF43AZl7PU%2Fimage.png?alt=media\&token=97965b43-04a7-4050-81d5-1313ec85eb70)

2.sqlconnection.h代码

```
// Some code
```

3.sqlconnection.cpp代码

```
// Some code
```

4.main.cpp主函数代码

```
// Some code
```

5.在main.qml文件中，导入注册类的命名空间，实例化对象，然后通过该对象的id来访问

该对象的属性和方法

```
// Some code
```

**方法2**

{% hint style="info" %}
参考资料：

<https://blog.csdn.net/qq_34139994/article/details/105195328>

<https://zhuanlan.zhihu.com/p/515424581?utm_id=0>

<https://www.cnblogs.com/ybqjymy/p/14270424.html>
{% endhint %}

（10）Qt6通过CMake连接SQL Server&#x20;

1. 配置好本机的ODBC
2. 参考帮助文档

![](https://3407761548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDFgj_K1oEIHPoXVkZG%2Fuploads%2FfvsltoLDrJQ9hOdOFtra%2Fimage.png?alt=media\&token=ea6d1660-41eb-4dfb-9fac-0cf577ec1867)

在CMakeLists.txt文件中添加如下两行，第一行添加sql模块，第二行添加Qt6::Sql

```
find_package(Qt6 6.2 COMPONENTS Quick REQUIRED Sql)
target_link_libraries(appKaoQin PRIVATE Qt6::Quick Qt6::Sql)
```

{% hint style="info" %}
参考资料：<https://www.bilibili.com/read/cv16264207/>
{% endhint %}

（11）报错处理

**提示：**

QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt\_sql\_default\_connection', old connection removed

**解决方案：**&#x8865;充如下代码

```
db.close();
QSqlDatabase::removeDatabase("QODBC");
```

{% hint style="info" %}
参考资料：<https://blog.csdn.net/wjian20/article/details/8472989>
{% endhint %}

（11）QT使用QSetting将MSSQL数据库通过写入注册表创建ODBC数据源

```
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QSqlDatabase>
#include <QSqlError>
#include<QSqlQuery>
#include <QSettings>
#include <QString>
#include<QDebug>

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

    QQmlApplicationEngine engine;
    const QUrl url(u"qrc:/StudyDemo01/main.qml"_qs);
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

//以下为正式内容
    //将数据库写入注册表
        //需要管理员权限运行
        QSettings reg_2("HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources", QSettings::NativeFormat);
        reg_2.setValue("dsnName","SQL Server");//dsnName为数据源名

        QSettings reg("HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI", QSettings::NativeFormat);
        reg.beginGroup("dsnName");
        reg.setValue("Driver","C:\\Windows\\system32\\SQLSRV32.dll");
        reg.setValue("Description","database");
        reg.setValue("Server","192.168.10.10");//主机IP地址
        reg.setValue("Database","ipinfo");//databaseName为默认数据库
        reg.setValue("LastUser","sa");//用户名
        reg.setValue("Trusted_Connection","No"); //Yes集成身份验证，No为混合身份验证
        reg.setValue("PWD","123456");

        QSettings reg_1("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MSSQLServer\\Client\\ConnectTo", QSettings::NativeFormat);
        reg_1.setValue("123.56.87.47","DBMSSOCN,192.168.10.10,1433");//1433为默认端口，可修改，只改IP，其他别动




    //连接MSSQL数据库
       QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");

       qDebug ()<< "sql driver "<< db.isValid();
       db.setHostName("192.168.10.10");
      //设置数据源名称
       db.setDatabaseName("dsnName");
       db.setUserName("sa");
       db.setPassword("123456");

       db.open();

       if(!db.open())
       {
           qDebug()<<db.lastError();
           //return false;


       }
       else
       {
           qDebug()<<"数据库连接成功！";
          //  return true;
           QSqlQuery query(db);

//           qDebug() << query.exec("select * from ipdata");

           query.exec("select * from ipdata");
           while(query.next())
           {
               qDebug() << query.value(0).toString() << query.value(1).toString();
           }

       }

//以上为正式内容
    return app.exec();
}

```

qDebug信息如下：

```
sql driver  true
数据库连接成功！
"物控" "192.168.10.100"
"销售" "192.168.10.1"
"销售" "192.168.10.2"
"直营部" "192.168.10.11"
"直营部" "192.168.10.11"
"直营部123" "192.168.10.11"
"直营部123" "192.168.10.11"
```

{% hint style="info" %}
参考资料：

QT使用QSetting将MSSQL数据库通过写入注册表创建ODBC数据源&#x20;

<https://blog.csdn.net/qq_38737205/article/details/116756356>

DSN 和连接字符串关键字和属性&#x20;

<https://docs.microsoft.com/zh-cn/sql/connect/odbc/dsn-connection-string-attribute?view=sql-server-ver16#authentication---sql_copt_ss_authentication>

<https://docs.microsoft.com/zh-cn/sql/relational-databases/native-client/applications/using-connection-string-keywords-with-sql-server-native-client?view=sql-server-ver16>

<https://blog.csdn.net/xftyyyyb/article/details/83188219>
{% endhint %}

<figure><img src="https://3407761548-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MDFgj_K1oEIHPoXVkZG%2Fuploads%2FW3XcNOI3nOvVk1UcdifD%2Fimage.png?alt=media&#x26;token=add39f3d-5f45-4243-8728-b89b9bad6ae8" alt=""><figcaption></figcaption></figure>

（12）
