QML初始化ComboBox遇到的问题

近期学习Qt,记录下学习过程,以免忘记。操作环境 WIN7+Qt 5.11.2。

新建 Qt Quick Application - Empty 项目,命名 ComboBoxDemo。

编辑 main.qml,添加 Rectangle 和 ComboBox。
main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello ComboBox")
    Rectangle{
        id:rect
        width: 200
        height: 200
        color:"red"
    }
    ComboBox{
        id:cb
        anchors.left: rect.right
        model:ListModel{
            id:cbmodel
            ListElement{
                text : "green"
            }
            ListElement{
                text : "blue"
            }
            ListElement{
                text : "yellow"
            }
        }
        onCurrentIndexChanged: {
            rect.color = cbmodel.get(cb.currentIndex).text;
        }
    }
    Component.onCompleted: {
        cb.currentIndex = 1
    }
}

目前为止一切正常,rect也有按预计的显示颜色。
现在我要把颜色存储下来,再次打开时显示存储的颜色。

编辑main.qml
main.qml

...
import QtQuick.LocalStorage 2.0
...
			onCurrentIndexChanged: {
            rect.color = cbmodel.get(cb.currentIndex).text;
            saveColor(cbmodel.get(cb.currentIndex).text);
        }
    }
    Component.onCompleted: {
        //cb.currentIndex = 1
        dbInit();
        var color = checkColor();
        console.log("color: " + color);

    }

    function dbInit(){
        var db = LocalStorage.openDatabaseSync("combo","1.0","ComboBox Database",100000);
        try{
            db.transaction(function(tx){
                tx.executeSql('CREATE TABLE IF NOT EXISTS combo(rect TEXT,color TEXT)');
            })
        } catch(err){
            console.log("Error creating table in database: " + err);
        };
    }
    function dbGetHandle()
    {
        try {
            var db = LocalStorage.openDatabaseSync("combo","1.0","ComboBox Database",100000);
        } catch (err) {
            console.log("Error opening database: " + err)
        }
        return db;
    }
    function saveColor(color){
        console.log("saveColor : " + color);
        var db = dbGetHandle();
        db.transaction(function(tx){
            tx.executeSql('UPDATE combo set color=? WHERE rect=?',[color,"rect"]);
        });
    }
    function checkColor(){
        var db = dbGetHandle();
        var color;
        var rs;
        var rowid = 0;
        db.transaction(function(tx){
            rs = tx.executeSql('SELECT * FROM combo WHERE rect="rect"');
        });
        if(rs.rows.length > 0)
        {
            color = rs.rows.item(0).color;
            return color;
        }else{
            db.transaction(function(tx){
                tx.executeSql('INSERT INTO combo VALUES(?,?)',["rect","red"]);
                rs = tx.executeSql('SELECT last_insert_rowid()')
                rowid = rs.insertId;
            });
            console.log("INSERT" + rowid);
            if(rowid > 0){
                return "red";
            }else{
                return 0;
            }
        }
    }

现在开始不正常了。
选择ComboBox颜色后,rect能正常显示对应颜色,数据库也存储正常。但是重新打开程序后,数据库被重置了,并不是之前选择的颜色,而是Model的第一个颜色:green。为什么会这样呢?

后来发现ComboBox在初始化的时候会触发onCurrentIndexChanged事件,将currentIndex=0的颜色存储下来。这个就不太好了…如何判断手动触发还是自动触发这个事件呢?

翻阅文档,发现这样一条信息:

activated(int = index)

This signal is similar to currentIndex changed, but will only be emitted if the combo box index was changed by the user, not when set programmatically.
index is the activated model index, or -1 if a new string is accepted.
The corresponding handler is onActivated.

替换 onCurrentIndexChanged 为 onActivated,问题解决。
最终代码:
main.qml

...
		onActivated: {
            rect.color = cbmodel.get(cb.currentIndex).text;
            saveColor(cbmodel.get(cb.currentIndex).text);
        }
    }
    Component.onCompleted: {
        //cb.currentIndex = 1
        dbInit();
        var color = checkColor();
        console.log("color: " + color);
        switch(color)
        {
        case "green" :
            cb.currentIndex = 0;
            break;
        case "blue" :
            cb.currentIndex = 1;
            break;
        case "yellow" :
            cb.currentIndex = 2;
            break;
        }
        rect.color = color;
    }
...

源码下载:https://download.csdn.net/download/weixin_43810973/10889373
学习中,多有不足,欢迎拍砖。

你可能感兴趣的:(QT,QML,ComboBox)