qml中ComboBox组件onCurrentIndexChanged与onActivated的使用

在qml页面中使用ComboBox时,一般会有以下用法:

json 复制代码
ComboBox{
	id: box
	model: yourBindingModel
	onCurrentIndexChanged: {   
		//业务代码
	}	
}  

通常不会有什么问题,切换下拉列表时触发onCurrentIndexChanged,然后执行业务代码。

但是,如果有

json 复制代码
currentIndex: yourBindingIndex

即给combox组件的currentIndex进行了数据绑定,那么在初始化UI时,如果yourBindingIndex有有效值,则会触发onCurrentIndexChanged,此时并不是我们手动操作下拉列表触发的,这种情况一般是预期以外的,onCurrentIndexChanged内业务代码的执行也会造成程序异常。那如何避免呢?

使用onActivated

json 复制代码
onActivated: {}

看官方文档描述:

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.

相关推荐
Quz20 小时前
QML 信号与槽:直接绑定与跨文件通信
qt·编程语言·设计
GIS阵地21 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
丰锋ff1 天前
1.2 Qt常用基础类型
开发语言·qt
nianniannnn1 天前
Qt QMessageBox知识点
开发语言·数据库·qt
J_yyy1 天前
【Qt核心组件类框架】
开发语言·qt
Drone_xjw1 天前
双网卡下Qt程序数据包“乱飞”之谜:为什么必须断开再连接
开发语言·qt
Quz1 天前
QML 网格与流式布局:Grid/GridLayout 与 Flow
qt
qq_401700411 天前
Qt容器性能优化:QVector、QHash、QMap到底应该怎么选?
开发语言·qt·性能优化
Quz1 天前
QML 线性布局:Row/RowLayout 与 Column/ColumnLayout
前端·qt
imatt2 天前
Qt Creator 在Windows下编译信息乱码
windows·qt