【发布时间】:2015-06-30 10:37:09
【问题描述】:
我正在尝试使用自定义元素实现某种自定义菜单。最终目标是创建某种带有文本和图标的弹出菜单。但是在创作过程中我遇到了一些问题。我可以展示 2 个主要问题:
- 在第一个位置有一个标题为
Hello world的奇怪菜单元素(看起来像是读取应用程序窗口的标题):
- 有时我会收到
qrc:/BreezeQuickMenu.qml:45: TypeError: Property 'clicked' of object QQuickListView(0x1120830) is not a function之类的错误
这是我的实际代码:
main.qml
import QtQuick 2.2
import QtQuick.Controls 1.1
import QtQuick.Window 2.2
ApplicationWindow {
title: qsTr("Hello World")
width: Screen.width
height: Screen.height
visible: true
id: win
color: brPalette.normalBackground
BreezeQuickMenu{
id: brMenu
x: 490
y: 199
width: 128
height: 256
palette: brPalette
menuFont.pointSize: 16
BreezeQuickMenuItem{
title: "Item 1"
onClicked: mbox.show()
}
BreezeQuickMenuItem{
title: "Item 2"
}
BreezeQuickMenuItem{
title: "Item 3"
}
}
}
BreezeQuickMenu.qml
import QtQuick 2.4
Item {
id: root
property BreezeQuickPalette palette: BreezeQuickPalette
property alias currentIndex: menuList.currentIndex
property font menuFont
property bool menuVisible: false
implicitWidth: 128
implicitHeight: menuList.height
ListView{
id: menuList
anchors.fill: parent
model: root.children
clip: true
delegate: Component {
id: menuItem
Rectangle {
id: menuElement
property bool isCurrentItem: ListView.isCurrentItem
anchors {
left: parent.left
right: parent.right
}
color: palette.normalBackground
height: menuText.font.pixelSize*1.2
Text {
id: menuText
anchors.fill: parent
text: title
color: palette.normalText
font: menuFont
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onClicked: {
menuList.currentIndex = index
menuList.model[index].clicked()
}
}
}
}
}
}
BreezeQuickMenuItem.qml
import QtQuick 2.4
Item {
id: root
property string title: "Menu Element"
signal clicked
}
如您所见,我正在尝试使用自己的信号实现菜单列表和菜单项。我有两个问题:
如何正确摆脱使用父元素的title属性,因为我需要读取children的title属性
在菜单元素中使用信号和槽以避免上述错误的正确方法是什么?
请帮助我理解。完整项目可以在这里拉取:
git clone git://git.code.sf.net/p/breezequick/code breezequick-code
【问题讨论】:
-
您缺少用于信号声明的
(),请参阅Signal to Signal Connect。避免使用与内置信号类似的名称,这可能会产生奇怪的错误。这不是你的情况,但最好避免潜在的问题来源。至于ListView,请考虑使用VisualItemModel或Object Instanced as models。 -
谢谢,真的很怀念这个东西。在其他元素中使用没有
()的信号名称(在QML 的几个Qt 教程中看到了这一点)。会为其他人解决这个问题。你的意思是我可以在没有委托的情况下使用VisualItemModel?但是在这种情况下,如何将菜单元素创建为子元素? (正如我在 main.qml 中展示的那样) -
使用孩子对我来说似乎很奇怪,因为
ListView本身也是root的孩子,不是吗?这对我来说听起来很尴尬。 -
明白,感谢您的建议。将尝试使用其他模型。
-
没问题,无论如何感谢您的提示。
标签: qt listview delegates qml qtquick2