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.

相关推荐
程序员编程指南6 小时前
Qt 数据库连接池实现与管理
c语言·数据库·c++·qt·oracle
晨风先生7 小时前
如何Visual Studio 的配置从 Qt-Debug 切换到 x64-Debug
ide·qt·visual studio
程序员编程指南9 小时前
Qt OpenGL 集成:开发 3D 图形应用
c语言·数据库·c++·qt·3d
钱彬 (Qian Bin)11 小时前
《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——6. 传统算法实战:用OpenCV测量螺丝尺寸
教程·cmake·qml·qt quick·工业软件·工业瑕疵检测·qt6.9.1
程序员编程指南11 小时前
Qt 网络编程进阶:RESTful API 调用
c语言·网络·c++·qt·restful
程序员编程指南12 小时前
Qt XML 与 JSON 数据处理方法
xml·c语言·c++·qt·json
程序员编程指南13 小时前
Qt 网络编程进阶:网络安全与加密
c语言·网络·c++·qt·web安全
2301_8035545214 小时前
【无标题】
开发语言·qt
程序员编程指南17 小时前
Qt字符串处理与正则表达式应用
c语言·c++·qt·正则表达式
啊呦.超能力1 天前
QT开发---多线程编程
开发语言·qt