【问题标题】:Change Font Size of Button in Qt QML在 Qt QML 中更改按钮的字体大小
【发布时间】:2014-09-29 13:08:51
【问题描述】:

如何在 QML 中设置 Button 控件中文本的字体大小?设计者没有选项,'font' 不是 Button 的有效属性。

Button {
    id: cmdQuit
    text: qsTr("Quit")
    width: 64
    height: 32
}

【问题讨论】:

    标签: qt qml qt-quick


    【解决方案1】:

    您设置了 Button 的 style 属性:

    import QtQuick 2.2
    import QtQuick.Controls 1.2
    import QtQuick.Controls.Styles 1.2
    
    Rectangle {
      id: container
      width: 800
      height: 800
    
      Button {
        id: cmdQuit
        text: qsTr("Quit")
        width: 64
        height: 32
        style: ButtonStyle {
          label: Text {
            renderType: Text.NativeRendering
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignHCenter
            font.family: "Helvetica"
            font.pointSize: 20
            color: "blue"
            text: control.text
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      对于 QtQuick 2,您必须使用 contentItem 属性,如下所示:https://doc.qt.io/qt-5/qtquickcontrols2-customize.html#customizing-button

      import QtQuick 2.12
      import QtQuick.Controls 2.12
      
      Button {
          id: control
          text: qsTr("Button")
      
          contentItem: Text {
              text: control.text
              font: control.font
              font.pointSize: 20
              opacity: enabled ? 1.0 : 0.3
              color: control.down ? "#17a81a" : "#21be2b"
              horizontalAlignment: Text.AlignHCenter
              verticalAlignment: Text.AlignVCenter
              elide: Text.ElideRight
          }
      }
      

      【讨论】:

        【解决方案3】:

        这是一个老问题,但由于它首先出现在搜索引擎中,所以我提供了有关情况的更新。

        对于 QtQuick2,与 Chris 所说的不同,您不再需要使用 contentItem 属性。您可以直接从Button 访问font 属性。

        例子:

        Button {
            id: btn
            text: "Test"
            font.pixelSize: 18
        }
        

        【讨论】:

        • 对于 Pyside6/Qt6,我认为不支持在接受的答案中使用样式属性,QtQuick.Controls.Styles 模块也不再可用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-16
        • 2011-02-24
        • 1970-01-01
        • 2019-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多