QML双击返回键弹窗后,取消再按返回键直接退出的修复条件咨询
Hey there! Let's sort out why your back button behavior goes wonky after canceling the popup. The core issue is that your backPressed flag and timer state aren't being properly reset when you close the popup via Cancel, plus the back key isn't handling the visible popup case correctly.
Here's what you need to adjust, along with the fixed code:
Key Fixes Needed
- Prioritize popup visibility in back key handling: When the popup is open, pressing back should just close the popup instead of triggering the double-press logic.
- Reset state on popup close: No matter how the popup is closed (Cancel button or back key), reset the
backPressedflag and stop the timer to ensure the next back press starts fresh. - Clean up timer state management: Make sure leftover press states don't carry over between interactions.
Fixed Code
Popup { visible: false id: popup background: Rectangle { width: 300; height: 200 } Row{ topPadding: 10 Button { text: qsTr("YES") onClicked: { Qt.quit(); } } Button{ text: qsTr("cancel") height:40 width:100 onClicked: { popup.close(); } } } modal: true focus: true // Reset back press state whenever the popup closes onClosed: { timer.backPressed = false; timer.stop(); } } // Adjust back key handling to check popup visibility first Keys.onBackPressed: { if (popup.visible) { popup.close(); } else { timer.pressBack(); } } Timer{ id: timer property bool backPressed: false repeat: false interval: 300 //ms onTriggered: backPressed = false function pressBack(){ if(backPressed){ timer.stop(); backPressed = false; popup.open(); } else{ backPressed = true; timer.start(); } } }
Breakdown of Changes
- Popup's
onClosedhandler: This ensures that every time the popup closes—whether via Cancel or the back key—we clear thebackPressedflag and stop the timer. This wipes any leftover state from the previous double-press attempt. - Updated
Keys.onBackPressed: Now it first checks if the popup is visible. If yes, it closes the popup directly. Only when the popup is hidden does it trigger the double-press logic, preventing the timer from getting confused. - Cleaned timer logic: Ensured the timer is stopped when we trigger the popup, so old timers don't interfere with new interactions.
With these tweaks, after canceling the popup, pressing the back key will start the double-press sequence fresh instead of immediately closing the app.
内容的提问来源于stack exchange,提问作者user13846567
相关产品推荐
相关产品推荐

