I am creating desktop application using QML and QtQuick.Components. I want to place on the toolbar buttons like the standard MacOS settings dialogs do:
I use ToolBar and ToolButton, but I can't find the way to do it. For instance with the following code it shows icons only:
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"
}
}
}
}
And it seems like ToolButton can show either text or icon:
Text {
id: textitem
text: button.text
anchors.centerIn: parent
visible: button.iconSource == "" // <=========
}
A simple yet a powerful approach is to create own QML component.
Create a custom QML component / file:File -> New File or Project -> Qt -> QML File (choose latest version)
.
Now enter file name, for example MyToolButton.
Note that it will be also used as
component name.
Add there neccesary imports and code:
MyToolButton.qml (customize for your needs)
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)
}
}
Main.QML (where you want to use it):
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"
}
Notes:
(optional)
can be skipped.ToolButton
with Button
and it will work as a Button. Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With