如何运行Qt文档中的QML StateMachine示例?遇显示异常求助
Troubleshooting Your Qt QML StateMachine Example Issues
Let's break down your problems one by one and fix them step by step, since you're working with Qt 5.9.2 and Qt Creator 4.4.1:
1. Fixing the "Button is not a type" error
- The
Buttoncomponent is part of theQtQuick.Controlsmodule, which wasn't imported in your initial code. Addingimport QtQuick.Controls 1.4(which you already did) is correct for Qt 5.9.2, as it matches the version compatibility for your Qt setup.
2. Fixing the "no window showing" issue
- Your original code used
Rectangleas the root component. In Qt Quick 2.x, a standaloneRectanglewon't automatically create a top-level window. Switching toWindow(from theQtQuick.Windowmodule) as the root component (like you did in your modified code) is the right solution—this component handles window creation and visibility.
3. Fixing the empty window + state machine failure
You have two separate issues here that caused the empty window and broken state machine:
a. Missing size configuration for the parent Rectangle
- In your modified code, the
Rectanglecontaining theButtonhas no size set. Since it doesn't fill the parentWindowby default, theButton(which usesanchors.fill: parent) ends up with zero size and is invisible. - Fix this by adding
anchors.fill: parentto theRectangleso it takes the full window space, making the button visible.
b. Typo in the State ID
- You named your
Statecomponentstate1, but theStateMachine'sinitialStateproperty referencesstate. This mismatch means the state machine can't find its starting state, breaking its initialization (and potentially causing unexpected UI behavior). - Correct the typo by changing the
State's id back tostate.
Fully Fixed Code
import QtQuick 2.8 import QtQuick.Window 2.2 import QtQuick.Controls 1.4 import QtQml.StateMachine 1.0 as DSM Window { visible: true width: 640 height: 480 title: qsTr("State Machine Demo") Rectangle { anchors.fill: parent // Ensure the rectangle fills the window Button { anchors.fill: parent id: button text: "Finish state" DSM.StateMachine { id: stateMachine initialState: state running: true DSM.State { id: state // Fixed the typo here DSM.SignalTransition { targetState: finalState signal: button.clicked } } DSM.FinalState { id: finalState } onFinished: Qt.quit() } } } }
This code will:
- Show a window with a full-size button
- Trigger the state transition when you click the button
- Close the app once the final state is reached
内容的提问来源于stack exchange,提问作者evadeflow
相关产品推荐
相关产品推荐

