Search code examples
qtqmlfocusscrollviewqt6

Can't set focus to ScrollView using Qt.ClickFocus


I just want my TextField to lose focus when i click on ScrollView, but the problem is scrollview does not accept the focus using Qt.ClickFocus.

import QtQuick
import QtQuick.Controls.Universal

ApplicationWindow {
    visible: true
    width: 600
    height: 400

    ScrollView {
        anchors.fill: parent
        focusPolicy: Qt.ClickFocus

        TextField {
            id: textField
            implicitWidth: 400
            implicitHeight: 50
        }
    }
}

I think there is something interfering the click event because when i use focusPolicy: Qt.TabFocus it works perfectly just fine.

I'm using Qt 6.5. Is this a freaking bug?

[Update] I just solve the problem using Stephen Quan answer

import QtQuick
import QtQuick.Controls.Universal
import QtQuick.Layouts

ApplicationWindow {
    visible: true
    width: 600
    height: 400

    ScrollView {
        id: scrollView
        anchors.fill: parent

        ColumnLayout {
            id: columnLayout
            TextField {
                Layout.preferredWidth: 400
            }
        }
        
        TapHandler { 
            onTapped: columnLayout.forceActiveFocus() 
        }
    }
}

I just used the columnLayout so I don't have to explicitly set contentWidth and contentHeight


Solution

  • You can also use a placeholder Item that's a child of the ScrollView as well as install a TapHandler for the ScrollView that calls that Item's forceActiveFocus():

        ScrollView {
            anchors.fill: parent
            TextField {
                id: textField
                implicitWidth: 400
                implicitHeight: 50
            }
            Item { id: placeholderItem }
            TapHandler { onTapped: placeholderItem.forceActiveFocus() }
        }
    

    You can Try it Online!