【问题标题】:Custom QML Quick 2 Control with TabBar Inside内部带有 TabBar 的自定义 QML Quick 2 控件
【发布时间】:2020-09-24 03:42:08
【问题描述】:

我正在 Qt 5.15 中创建自定义 QML Quick 2 TabBar 控件。如果我将一个简单的控件(CustomTabBarSimple.qml)设为

import QtQuick 2.0
import QtQuick.Controls 2.15
TabBar {
}

然后我可以使用它

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15

Window {
    visible: true
    width: 640; height: 480
    color:"silver"

    CustomTabBarSimple
    {
        id:bar
        TabButton { text:"Button1" }
        TabButton { text:"Button2" }
    }

    StackLayout {
        anchors.top: bar.bottom
        currentIndex: bar.currentIndex
        Text {text: "First Stack"}
        Text {text: "Second Stack"}
    }
}

但是,如果我将 TabBar 包装在另一个控件中,这样就不再起作用了:

import QtQuick 2.0
import QtQuick.Controls 2.15

Rectangle
{
    default property alias contents: bar.data

    width: 300; height:50
    color: "red"

    TabBar {
        id: bar
    }
}

您可以看到我尝试使用default property alias contents: bar.dataTabButton 放在自定义控件的TabBar 中,但似乎TabBar 不再正确组织按钮并且它们不再更改currentIndex 时点击——可能是因为 data 字段正在覆盖关键元素。

是否可以使用默认别名将TabButton 注入正确的位置?其次,我怎样才能从文档中自己发现这一点?

【问题讨论】:

  • 如果在id: bar 之后添加anchors.fill: parent 会发生什么?

标签: qt qml


【解决方案1】:

您的代码有两个问题:

  1. 您正在尝试从 TabBar 访问 currentIndex,但您没有在 CustomTabBarSimple 中公开该属性。您可以通过添加以下内容来解决此问题:
property alias currentIndex: bar.currentIndex
  1. TabButton 列表不是 TabBar 的直接子级。 TabBar 派生自一个Container,它在contentData 中有一个子对象列表。你可以阅读here
default property alias contents: bar.contentData

【讨论】:

  • 这是正确的。但是,从文档链接中不清楚这是否会起作用。您/我们如何在不需要专家意见的情况下知道这是真的?在容器中替换列表直到它起作用之前肯定是不可接受的吗?
  • 是的,文档没有描述每个细节或用例。但 Qt 也是开源的。在找到它的文档之前,我实际上在源代码中找到了这个答案。
猜你喜欢
  • 2013-07-24
  • 1970-01-01
  • 2014-06-11
  • 2011-09-08
  • 1970-01-01
  • 2020-07-28
  • 2015-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多