QML TableView 2.15 行点击、双击和右键菜单实现 - 使用 Keys.onPressed
在 QML 的 TableView 中,可以使用 Keys.onPressed 来实现行的点击、双击和右键菜单功能。下面是一个示例代码:\n\nqml\nimport QtQuick 2.15\nimport QtQuick.Controls 2.15\nimport QtQuick.Layouts 1.15\n\nTableView {\n id: tableView\n width: 400\n height: 300\n model: myModel\n\n TableViewColumn {\n role: "name"\n title: "Name"\n }\n\n TableViewColumn {\n role: "age"\n title: "Age"\n }\n\n Keys.onPressed: {\n if (event.key === Qt.Key_Return) {\n // 处理行点击事件\n var rowIndex = tableView.currentIndex.row\n console.log("Row clicked: " + rowIndex)\n } else if (event.key === Qt.Key_Enter) {\n // 处理行双击事件\n var rowIndex = tableView.currentIndex.row\n console.log("Row double-clicked: " + rowIndex)\n } else if (event.key === Qt.Key_Menu) {\n // 处理右键菜单事件\n var rowIndex = tableView.currentIndex.row\n console.log("Row right-clicked: " + rowIndex)\n }\n }\n\n // 添加右键菜单\n contextMenuPolicy: Qt.CustomContextMenu\n onCustomContextMenuRequested: {\n var rowIndex = tableView.currentIndex.row\n console.log("Row right-clicked: " + rowIndex)\n\n // 创建菜单\n var menu = Menu {\n MenuItem {\n text: "Action 1"\n onTriggered: console.log("Action 1 triggered")\n }\n MenuItem {\n text: "Action 2"\n onTriggered: console.log("Action 2 triggered")\n }\n }\n menu.popup()\n }\n}\n\nListModel {\n id: myModel\n ListElement {\n name: "John"\n age: 25\n }\n ListElement {\n name: "Jane"\n age: 30\n }\n}\n\n\n在这个示例中,我们使用 Keys.onPressed 处理键盘事件。当按下回车键时,会输出当前点击行的索引;当按下 Enter 键时,会输出当前双击行的索引;当按下菜单键时,会输出当前右击行的索引。\n\n另外,我们还通过设置 contextMenuPolicy 为 Qt.CustomContextMenu 来启用右键菜单功能,并在 onCustomContextMenuRequested 信号中实现了右键菜单的内容和动作。在这个示例中,右键菜单包含两个动作 Action 1 和 Action 2,当点击相应的菜单项时,会输出相应的信息。\n\n注意:在 QML 中,TableView 的键盘事件只有在 TableView 聚焦时才能触发。可以通过设置 focus 为 true 来设置 TableView 聚焦。
原文地址: https://www.cveoy.top/t/topic/pTLA 著作权归作者所有。请勿转载和采集!