首页 > 解决方案 > 基于ScrollBar如何使用鼠标滚轮滑动QML页面?

问题描述

我尝试创建一个子窗口来显示窗口无法完全显示的文章。目前,我可以通过拖动ScrollBar(QML 类型)来滑动页面,但我也想使用鼠标滚轮来滑动它。

这是代码:

import QtQuick 2.2
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

Window {
    id:privacyWindow
    width: 640
    height: 480
    title:qsTr("Privacy")

    Rectangle {
        id: privacy
        clip: true
        width: privacyWindow.width
        height: privacyWindow.height
        anchors.centerIn: parent

        Rectangle {
            id: textArea
            clip: true
            width: privacyWindow.width - 150
            height: privacyWindow.height
            anchors.centerIn: parent

            Text {
                id: content
                width: textArea.width
                text: ""
                wrapMode: Text.WordWrap
                textFormat: Text.RichText
                //x: -horizontalBar.position * width
                y: -verticalBar.position * height
            }
        }

        ScrollBar {
            id: verticalBar
            hoverEnabled: true
            active: hovered || pressed
            orientation: Qt.Vertical
            size: privacy.height / content.height
            anchors.top: parent.top
            anchors.right: parent.right
            anchors.bottom: parent.bottom
        }
    }
}

任何帮助将不胜感激!谢谢你。:)

标签: qtqmlqtquick2

解决方案


我设法通过用 Flickable 替换Rectangle解决它。

import QtQuick.Controls 2.12

Window {
    id: privacyWindow
    width: 640
    height: 480
    title:qsTr("Privacy")

    Flickable {
        id: flickable
        clip: true
        width: privacyWindow.width - 150
        height: privacyWindow.height
        contentWidth: content.width
        contentHeight:content.height
        anchors.centerIn: parent

        Text {
            id: content
            width: flickable.width
            text: ""
            wrapMode: Text.WordWrap
            textFormat: Text.RichText
        }

        ScrollBar.vertical: ScrollBar {
            parent: flickable.parent
            anchors.top: parent.top
            anchors.right: parent.right
            anchors.bottom: parent.bottom
        }
    }
}

推荐阅读