我正在使用QML和QtQuick.Components创建桌面应用程序。我想像标准MacOS设置对话框一样放置在工具栏按钮上:
我使用ToolBar和ToolButton,但是找不到解决方法。例如,使用以下代码,它仅显示图标:
ApplicationWindow {
// ...
toolBar: ToolBar {
RowLayout {
ToolButton {
text: qsTr("Main")
iconSource: "main.png"
}
ToolButton {
text: qsTr("System")
iconSource: "system.png"
}
ToolButton {
text: qsTr("Items Book")
iconSource: "itemsbook.png"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
而且看来ToolButton可以显示文本或图标:
Text {
id: textitem
text: button.text
anchors.centerIn: parent
visible: button.iconSource == "" // <=========
}
Run Code Online (Sandbox Code Playgroud)
一种简单而强大的方法是创建自己的QML组件。
创建一个自定义QML组件/文件:
File -> New File or Project -> Qt -> QML File (choose latest version)
。
现在输入文件名,例如MyToolButton。
注意,它也将用作
组件名称。
在其中添加必要的导入和代码:
MyToolButton.qml(根据您的需求定制)
import QtQuick 2.0
import QtQuick.Controls 1.4
ToolButton
{
Image {
source: parent.iconSource
fillMode: Image.PreserveAspectFit // For not stretching image (optional)
anchors.fill: parent
anchors.margins: 2 // Leaving space between image and borders (optional)
anchors.bottomMargin:10 // Leaving space for text in bottom
}
Text {
text: parent.text
anchors.bottom: parent.bottom // Placing text in bottom
anchors.margins: 2 // Leaving space between text and borders (optional)
anchors.horizontalCenter: parent.horizontalCenter // Centering text
renderType: Text.NativeRendering // Rendering type (optional)
}
}
Run Code Online (Sandbox Code Playgroud)
Main.QML(要使用它的地方):
import QtQuick 2.0
import QtQuick.Controls 1.4
// Usual toolbar declaration
ToolBar {
id: mainToolBar
RowLayout {
// Create MyToolButton. Note that component name (MyToolButton) is the same as file name.
MyToolButton {
id:tbQuit
// Way 1: Add here any icon
iconSource: "qrc:///images/quit.png"
text:qsTr("&Quit")
// Way 2, my favourite: Convert your Action into Button!
action: actQuit
}
}
}
Action {
id: actQuit
text: qsTr("&Quit")
onTriggered: Qt.quit()
shortcut: "Alt+Q"
iconSource: "qrc:///Images/Exit.png"
}
Run Code Online (Sandbox Code Playgroud)
笔记:
(optional)
可以跳过。ToolButton
为Button
,它将用作按钮。 希望能帮助到你!
小智 4
Text
您是否尝试像这样添加自己的控件:
ApplicationWindow {
// ...
toolBar: ToolBar {
RowLayout {
ToolButton {
text: qsTr("Main")
iconSource: "main.png"
Text {
text: parent.text
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
}
}
ToolButton {
text: qsTr("System")
iconSource: "system.png"
Text {
text: parent.text
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
}
}
ToolButton {
text: qsTr("Items Book")
iconSource: "itemsbook.png"
Text {
text: parent.text
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并设置ToolButton
正确的高度(图像+文字高度)