void MainWindow::on_device_item_clicked(QTreeWidgetItem* item, int column) {
	 if (item->flags() & Qt::ItemIsUserCheckable) {
		 if (item->childCount() > 0) {
			 if (Qt::Checked == item->checkState(0)) {
				 item->setBackground(0, m_brush_white);
				 item->setBackground(1, m_brush_white);
				 item->setCheckState(0, Qt::Unchecked);
				 ui.action_connect->setEnabled(false);
			 } else {
				 item->setBackground(0, m_brush_red);
				 item->setBackground(1, m_brush_red);
				 item->setCheckState(0, Qt::Checked);
				 ui.action_connect->setEnabled(true);
				 QString devName = item->text(1);
				 if (devName.startsWith('Codesys', Qt::CaseInsensitive)) {
					 QPixmap pixmap(':/app/codesys');
					 ui.device_image->setPixmap(pixmap);
					 ui.device_image->setFixedHeight(pixmap.height());
				 } else if (devName.startsWith('vpoc', Qt::CaseInsensitive)) {
					 QPixmap pixmap(':/app/mpoc');
					 ui.device_image->setPixmap(pixmap);
					 ui.device_image->setFixedHeight(pixmap.height());
				 }
			 }

			 QTreeWidgetItem* otherItem;
			 for (int n = 0; n < ui.deviceTreeWidget->topLevelItemCount(); n++) {
				 otherItem = ui.deviceTreeWidget->topLevelItem(n);
				 if (item == otherItem)
					 continue;

				 otherItem->setBackground(0, m_brush_white);
				 otherItem->setBackground(1, m_brush_white);
				 otherItem->setCheckState(0, Qt::Unchecked);
			 }
			 bool selected = false;
			 qDebug() << 'Selected:' << ui.deviceTreeWidget->selectedItems().size();
			 for (int n = 0; n < ui.deviceTreeWidget->topLevelItemCount(); n++) {
				 otherItem = ui.deviceTreeWidget->topLevelItem(n);
				 if (otherItem->checkState(0) == Qt::Checked) {
					 selected = true;
					 break;
				 }
			 }
			 if (!selected) {
				 ui.device_image->setFixedHeight(0);
			 }
		 }
	 }
}

代码解析:

  1. 检查项目是否可选: if (item->flags() & Qt::ItemIsUserCheckable)
  2. 判断项目是否有子项: if (item->childCount() > 0)
  3. 根据项目选中状态更新界面:
    • 选中状态: 背景颜色设置为红色, 复选框状态为已选中, 连接操作启用
    • 未选中状态: 背景颜色设置为白色, 复选框状态为未选中, 连接操作禁用
  4. 更新设备图像: 根据设备名称显示对应图像
  5. 取消其他项目选中状态: 遍历所有其他可选项目, 将其背景颜色设置为白色, 复选框状态设置为未选中
  6. 更新设备图像高度: 根据当前所选项目数, 确定是否更新设备图像高度

功能: 该代码实现了一个设备树的交互逻辑,包括选中状态切换、界面更新等功能。

应用场景: 该代码片段适用于使用 Qt 开发的程序中, 用于处理设备树中项目的点击事件, 实现用户交互和界面更新。

代码优化建议:

  • 使用更具描述性的变量名, 例如 item 可以改为 clickedItem
  • 可以使用 Qt 的信号槽机制来简化代码逻辑
  • 可以将更新界面逻辑封装成独立的函数,提高代码可读性和可维护性
  • 可以使用 QAbstractItemModel 来管理设备树数据,提高代码的灵活性
Qt 程序设备树点击事件处理函数 - on_device_item_clicked() 代码解析

原文地址: https://www.cveoy.top/t/topic/mTEk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录