覆盖QML行的MouseArea(或自动调整图像大小和文本大小)

Phr*_*ogz 4 qt qml

摘要:如何在文本旁边贴上一个图标,而无需对尺寸进行硬编码,并以MouseArea...的方式将它们都包裹起来,从而可以在...内工作GridLayout?


我创建了一个QML布局,在可轻敲的“按钮”上有多个标签行。这些按钮是带有文字的图标:

两行两列; 最右边的列内嵌图像和文本

为了创建按钮,我使用Row,以便两个项目正确地粘在一起(没有任何硬编码的尺寸),并具有GridLayout可以使用的自动大小:

GridLayout {
  columns:2; rowSpacing:30

  Text {
    text: audioServer.label
    Layout.alignment: Qt.AlignLeft
  }

  Row {
    spacing:10; Layout.alignment:Qt.AlignRight
    Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
    Text  { text:"Find Another" }
  }

  Text {
    text: "System uptime "+system.uptime
    Layout.alignment: Qt.AlignLeft
  }

  Row {
    spacing:10; Layout.alignment:Qt.AlignRight
    Image { width:29; height:30; y:10; source:"qrc:/restart.png" }
    Text  { text: "Restart" }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想MouseArea在每个按钮周围放一个。如果我把它放在一排,像这样...

Row {
  Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
  Text  { text:"Find Another" }

  MouseArea {
    anchors.fill: parent
    onClicked: rescan()
  }
}
Run Code Online (Sandbox Code Playgroud)

...然后我得到(合理的)错误,QML Row: Cannot specify left, right, horizontalCenter, fill or centerIn anchors for items inside Row. Row will not function.而且更重要的是,布局中断了(我认为Row的宽度为零,因此GridLayout使其从右侧流出。)

我不能像这样移动MouseArea外部GridLayout...

GridLayout {
  ...
  Row {
    id: rescanButton
    Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
    Text  { text:"Find Another" }
  }
}
MouseArea {
  anchors.fill: rescanButton
  onClicked: rescan()
}
Run Code Online (Sandbox Code Playgroud)

...因为您只能锚定于兄弟姐妹或父母。

但是我不能将放在MouseArea里面GridLayout,因为那样的话它将尝试将其作为项目布置。

如何获得包裹按钮的MouseArea?

使用除以外的其他容器对我来说是可以接受的Row,但是我强烈不希望对任何文本或容器尺寸进行硬编码。

Fil*_*ski 6

在您的帮助下,我们得到了:

GridLayout {
  ...
  MouseArea {
    onClicked: rescan()
    width:  childrenRect.width
    height: childrenRect.height
    Row {
      Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
      Text  { text:"Find Another" }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)