Lab Exercise 7 (QML Widgets)
Lab Exercise 7 (QML Widgets)
ApplicationWindow {
visible: true
width: 400
height: 200
title: "Widget Example"
Label {
text: "Hello, QML Widgets!"
anchors.centerIn: parent
}
}
Here, we import the QtQuick.Controls module for creating widgets. We've added a
Label widget with the text "Hello, QML Widgets!" centered within the window.
Step 3: Running the Application
Build and run your application. You should see a window displaying the label.
Step 4: Creating a Button Widget
Let's add a button widget that displays a message when clicked.
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 400
height: 200
title: "Widget Example"
Label {
text: "Hello, QML Widgets!"
anchors.centerIn: parent
}
Button {
text: "Click Me"
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: label.bottom
onClicked: {
label.text = "Button Clicked!"
}
}
}
We added a Button widget with the text "Click Me" and a Label with the initial text.
When the button is clicked, it changes the label's text.
Step 5: Creating an Input Field (TextField) Widget
Next, let's add an input field where users can enter text.
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
visible: true
width: 400
height: 200
title: "Widget Example"
Label {
text: "Hello, QML Widgets!"
anchors.centerIn: parent
}
Button {
text: "Click Me"
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: label.bottom
onClicked: {
label.text = "Button Clicked!"
}
}
TextField {
placeholderText: "Enter text"
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: button.bottom
onTextChanged: {
label.text = "You entered: " + text
}
}
}
We've added a TextField widget with a placeholder text "Enter text." When the text in
the input field changes, it updates the label with "You entered: " followed by the
entered text.
Step 6: Running the Final Application
Build and run your application again. You should now see a label, a button, and an
input field.
This tutorial covers the basics of creating and using widgets in QML. You can explore
more widgets and their properties in the Qt documentation
(https://doc.qt.io/qt-5/qmltypes.html).