Qt 如何在不使用id的情况下从ButtonStyle获取父按钮?
我创建了一个组件(SidebarMenuButton),它在主qml文件中多次使用。按钮的样式应由其所有“实例”继承。以下是SidebarMenuButton.qml:Qt 如何在不使用id的情况下从ButtonStyle获取父按钮?,qt,qml,Qt,Qml,我创建了一个组件(SidebarMenuButton),它在主qml文件中多次使用。按钮的样式应由其所有“实例”继承。以下是SidebarMenuButton.qml: import QtQuick 2.3 import QtQuick.Controls 1.2 import QtQuick.Controls.Styles 1.2 Button { width: buttonNewMessage.width height: buttonNewMessage.height
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
Button {
width: buttonNewMessage.width
height: buttonNewMessage.height
anchors {
horizontalCenter: parent.horizontalCenter
topMargin: 5
}
style: ButtonStyle {
background: Rectangle {
color: 'transparent'
}
label: Text {
text: parent.text // undefined here
color: 'white'
font.family: 'Helvetica'
font.pixelSize: 12
font.bold: true
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
}
}
以及我的主qml文件的一部分:
import QtQuick 2.3
import QtQuick.Window 2.1
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
Window {
id: main
title: 'Messenger'
width: 1024
height: 768
minimumWidth: 800
minimumHeight: 600
RowLayout {
id: layout
anchors.fill: parent
spacing: 0
Rectangle {
id: sidebar
color: '#3C3E55'
Layout.fillHeight: true
Layout.preferredWidth: 200
ButtonCompanyName {
id: buttonCompanyName
}
ButtonNewMessage {
id: buttonNewMessage
}
SidebarMenuButton {
id: buttonInbox
text: 'Inbox (1)'
anchors.top: buttonNewMessage.bottom
}
SidebarMenuButton {
id: buttonSentMessages
text: 'Sent messages'
anchors.top: buttonInbox.bottom
}
SidebarMenuButton {
id: buttonStarred
text: 'Starred'
anchors.top: buttonSentMessages.bottom
}
}
我对这行的注释有误。父项没有引用按钮,因此所有按钮中的文本都为空。我需要访问父按钮,从那里得到它的文本属性。组件没有id,因为它被多次使用,并且id在主qml文件中分配。因此,问题是:没有id如何获取按钮文本?您可以在组件文件中指定一个
id
,该id不会与您在其他地方实例化组件时使用的id冲突。我对大多数QML组件的id使用相同的值:container
,这样我就可以轻松地从项的根引用属性
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
Button {
id: container
style: ButtonStyle {
background: Rectangle {
color: 'transparent'
}
label: Text {
text: container.text
}
}
}
然后,当您在另一个文件中实例化此组件时,您可以设置所需的id,并且它仍然可以工作在您的案例中有两种设置文本的方法 1) 应用样式的按钮在
ButtonStyle
类中作为control
属性提供。您可以将文本设置为text:control.text
2) 您可以为侧栏菜单按钮
中的按钮
指定id,并访问其文本
属性
Button
{
id:button
.
.
.
text: button.text
}