问题很简单:如何使用QML和javascript创建上下文菜单? 我在qt-project.org上找到了关于“菜单”组件的手册,但很不可用:http://qt-project.org/doc/qt-5.1/qtquickcontrols/qml-qtquick-controls1-menu.html#details
Qt Creator IDE在我的QML文件中的“菜单”一词上写着:“未知组件”。我正在使用Qt 5.2.1稳定。我正在使用Qt Quick 2进行编码。
答案 0 :(得分:8)
需要与Qt Quick一起导入Qt Quick Controls:
import QtQuick 2.0
import QtQuick.Controls 1.1
对于上下文菜单,您需要调用popup()
来打开光标位置的菜单。
答案 1 :(得分:1)
我为桌面应用程序创建了一个自定义上下文菜单。这对我来说非常合适。我认为这可能会有所帮助。
ContextMenu.qml
import QtQuick 1.1
Rectangle {
id: contextMenuItem
signal menuSelected(int index) // index{1: Select All, 2: Remove Selected}
property bool isOpen: false
width: 150
height: menuHolder.height + 20
visible: isOpen
focus: isOpen
border { width: 1; color: "#BEC1C6" }
Column {
id: menuHolder
spacing: 1
width: parent.width
height: children.height * children.length
anchors { verticalCenter: parent.verticalCenter; left: parent.left; leftMargin: 3 }
ContextButton {
id: selectedAll
button_text: "Select All"
index: 1
onButtonClicked: menuSelected(index);
}
ContextButton {
id: removeSelected
button_text: "Remove Selected"
index: 2
onButtonClicked: menuSelected(index);
}
}
}
ContextItem.qml
import QtQuick 1.1
Item {
id: contextButtonItem
property string button_text;
property bool clicked;
property int index;
property string target;
property bool enable: true;
signal buttonClicked;
height: 25
width: parent.width - 5
function viewButtonHovered() {
viewButton.state = "hovered";
outerArea.z= -10;
}
function viewButtonExited() {
outerArea.z= 1;
if(clicked == false) {
viewButton.state = "";
} else {
viewButton.state = "clicked"
}
}
Rectangle {
id: viewButton;
height: vButton.height + 4
width: parent.width
Text {
id: vButton
text: qsTr(button_text)
width: parent.width
anchors { verticalCenter: parent.verticalCenter; left: parent.left; leftMargin: 10 }
font { pixelSize: 14 }
}
MouseArea {
hoverEnabled: enable
anchors.fill: parent
enabled: enable
onClicked: buttonClicked();
onEntered: viewButtonHovered();
onExited: viewButtonExited();
}
states: [
State {
name: "clicked";
PropertyChanges { target: vButton; color: "#286E1E"; }
},
State {
name: "hovered";
PropertyChanges { target: vButton; color: "#BEA1C6"; }
},
State {
name: "normal";
PropertyChanges { target: vButton; color: "#232323"; }
}
]
}
}