x
Ақп. 8, 2018, 6:22 Т.Қ.

Как в QML поменять цвет кнопки Button?

button, qml, кнопка, цвет

Не могу понять простую вещь: как в QML поменять цвет кнопки для типа Button из набора QtQuick.Controls 1.5

Я создаю свой тип кнопки так (файл MyPrettyButton.qml):

import QtQuick 2.0
import QtQuick.Controls 1.5
import QtQuick.Controls.Styles 1.4

Button {

    style: ButtonStyle {
        background: Rectangle {
            color: control.pressed ? "#989898" : "#a4ab90"
        }
    }
}

Но когда я использую такой тип, внешний вид кнопки сильно меняется:

  • Кнопка сплющивается раза в полтора по высоте
  • Иконка (задаваемая через iconSource) начинает прилипать к тексту надписи, вместо того чтобы находиться в левой части кнопки
Зато цвет кнопки меняется правильно.

Вопрос: как поменять цвет кнопки, не затрагивая ничего другого?
4

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

11
Evgenii Legotckoi
  • Ақп. 8, 2018, 6:31 Т.Қ.

Добрый день!

А никак... Внешний вид в старых контролах настраивается только через стили со всеми вытекающими последствиями.
Поэтому если хотите что-то одно переопределить, то переопределять придётся всё сразу.
Button {
    text: "A button"
    style: ButtonStyle {
        background: Rectangle {
            implicitWidth: 100
            implicitHeight: 25
            border.width: control.activeFocus ? 2 : 1
            border.color: "#888"
            radius: 4
            gradient: Gradient {
                GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
                GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
            }
        }
    }
}
    BlinCT
    • Ақп. 8, 2018, 7:48 Т.Қ.

    Вообще я бы посоветовал уже использовать 2 контролы. Потому что уже 2.2 версия есть. С ними проще все.
    Вот мой пример костомной кнопки если вдруг потребуется.

    Button
    {
        id: control
        text: qsTr("Button")
    
        contentItem: Text {
            text: control.text
            font: control.font
            opacity: enabled ? 1.0 : 0.3
            color: control.down ? "#FA8072" : "#696969"
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
            elide: Text.ElideRight
        }
    
        background: Rectangle {
            implicitWidth: 90
            implicitHeight: 30
            opacity: enabled ? 1 : 0.3
            border.color: control.down ? "#FA8072" : "#696969"
            border.width: 1
            radius: 4
        }
    }
      Михаиллл
      • Маусым 28, 2019, 5:12 Т.Қ.
      • (өңделген)

      Сделал так, но у меня цвет кнопки становится всегда белым, не зависимо от выбранного цвета. Скажите пожалуйста, почему так?

              background: Rectangle {
                  implicitWidth: 90
                  implicitHeight: 30
                  opacity: enabled ? 1 : 0.3
                  border.color: control.down ? "blue" : "chartreuse"
                  border.width: 1
                  radius: 4
                  }
      

      А если делаю так, то кнопка становится белой и текст исчезает

          Button {
              id: page0Button0
              x: 58
              y: 80
              text: qsTr("1 из 2 цветов")
              //autoRepeat: false
              //display: AbstractButton.TextBesideIcon
      
              contentItem: Text {
                  text: control.text
                  font: control.font
                  opacity: enabled ? 1.0 : 0.3
                  color: control.down ? "#red" : "#black"
                  horizontalAlignment: Text.AlignHCenter
                  verticalAlignment: Text.AlignVCenter
                  elide: Text.ElideRight
              }
      
              background: Rectangle {
                  implicitWidth: 90
                  implicitHeight: 30
                  opacity: enabled ? 1 : 0.3
                  border.color: control.down ? "blue" : "chartreuse"
                  border.width: 1
                  radius: 4
              }
          }
      

      А если сделать так, то цвет меняется. Но как добаить другой цвет при нажатии?

              background: Rectangle {
                  implicitWidth: 90
                  implicitHeight: 30
                  opacity: enabled ? 1 : 0.3
                  color: "red"
                  border.color:  "blue"
                  border.width: 1
                  radius: 4
              }
      

      Если делаю так, то получаю ошибку: неверное название свойства "style"

       style: ButtonStyle {
              background: Rectangle {
                  implicitWidth: 100
                  implicitHeight: 25
                  border.width: control.activeFocus ? 2 : 1
                  border.color: "#888"
                  radius: 4
                  gradient: Gradient {
                      GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
                      GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
                  }
              }
          }
      
        Evgenii Legotckoi
        • Шілде 1, 2019, 12:45 Т.Қ.

        Добрый день!

        Свойство style есть только в старых контролах версии 1, в новых контролах style нет, просто переопределяет contentItem как вы делали в первом вариаанте.

        У вас там проблема в том, что вы зачем-то решётку добавили. Она там не должна находиться, так будет преавильно.

            Button {
                id: page0Button0
                x: 58
                y: 80
                text: qsTr("1 из 2 цветов")
                //autoRepeat: false
                //display: AbstractButton.TextBesideIcon
        
                contentItem: Text {
                    text: control.text
                    font: control.font
                    opacity: enabled ? 1.0 : 0.3
                    color: control.down ? "red" : "black"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    elide: Text.ElideRight
                }
        
                background: Rectangle {
                    implicitWidth: 90
                    implicitHeight: 30
                    opacity: enabled ? 1 : 0.3
                    border.color: control.down ? "blue" : "chartreuse"
                    border.width: 1
                    radius: 4
                }
            }
        
          Михаиллл
          • Шілде 1, 2019, 3:23 Т.Қ.

          Вставил Ваш код, вышло так, но кнопка становится белой и текст уже не видно

              Button {
                  id: page0Button0
                  y: parent.height * 0.16
                  width: parent.width * 0.3
                  height: parent.height * 0.08
                  text: qsTr("1 of 2 colors") //"1 из 2 цветов"
                  anchors.left: parent.left
                  anchors.leftMargin: parent.width * 0.14
                  //autoRepeat: false
                  //display: AbstractButton.TextBesideIcon
          
                  /*background: Rectangle {
                      implicitWidth: 90
                      implicitHeight: 30
                      opacity: enabled ? 1 : 0.3
                      color: "#e4e4ff"
                      border.color:  "black"
                      border.width: 1
                      radius: 4
                  }*/
                  contentItem: Text {
                              text: control.text
                              font: control.font
                              opacity: enabled ? 1.0 : 0.3
                              color: control.down ? "red" : "black"
                              horizontalAlignment: Text.AlignHCenter
                              verticalAlignment: Text.AlignVCenter
                              elide: Text.ElideRight
                          }
          
                          background: Rectangle {
                              implicitWidth: 90
                              implicitHeight: 30
                              opacity: enabled ? 1 : 0.3
                              border.color: control.down ? "blue" : "chartreuse"
                              border.width: 1
                              radius: 4
                          }
              }
          
            Evgenii Legotckoi
            • Шілде 1, 2019, 3:29 Т.Қ.

            Сдаётся мне, что вы взяли control.down из старой версии контролов. перепишите так

                Button {
                    id: page0Button0
                    y: parent.height * 0.16
                    width: parent.width * 0.3
                    height: parent.height * 0.08
                    text: qsTr("1 of 2 colors") //"1 из 2 цветов"
                    anchors.left: parent.left
                    anchors.leftMargin: parent.width * 0.14
            
                    contentItem: Text {
                                text: control.text
                                font: control.font
                                opacity: enabled ? 1.0 : 0.3
                                color: pressed ? "red" : "black"
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                                elide: Text.ElideRight
                            }
            
                            background: Rectangle {
                                implicitWidth: 90
                                implicitHeight: 30
                                opacity: enabled ? 1 : 0.3
                                border.color: pressed ? "blue" : "chartreuse"
                                border.width: 1
                                radius: 4
                            }
                }
            
              Михаиллл
              • Шілде 1, 2019, 3:44 Т.Қ.
              • (өңделген)

              Переписал, тот же результат, все та же белаю кнопка

              Разве Ваш код не повторяет предыдущий?

              Вот код: с начала файла

              import QtQuick 2.12
              import QtQuick.Controls 2.12
              //import QtQuick.Controls.Styles 1.4
              
              Item {
                  id: element
                  width: 400
                  height: 600
                  property alias page0Button6: page0Button6
                  property alias page0Button5: page0Button5
                  property alias page0Button4: page0Button4
                  property alias page0Button3: page0Button3
                  property alias page0Button2: page0Button2
                  property alias page0Button1: page0Button1
                  property alias page0Button0: page0Button0
                  property alias pag0Label1: pag0Label1
              
              
                  Button {
                      id: page0Button0
                      y: parent.height * 0.16
                      width: parent.width * 0.3
                      height: parent.height * 0.08
                      text: qsTr("1 of 2 colors") //"1 из 2 цветов"
                      anchors.left: parent.left
                      anchors.leftMargin: parent.width * 0.14
                      //autoRepeat: false
                      //display: AbstractButton.TextBesideIcon
              
                      /*background: Rectangle {
                          implicitWidth: 90
                          implicitHeight: 30
                          opacity: enabled ? 1 : 0.3
                          color: "#e4e4ff"
                          border.color:  "black"
                          border.width: 1
                          radius: 4
                      }*/
                      contentItem: Text {
                                  text: control.text
                                  font: control.font
                                  opacity: enabled ? 1.0 : 0.3
                                  color: pressed ? "red" : "black"
                                  horizontalAlignment: Text.AlignHCenter
                                  verticalAlignment: Text.AlignVCenter
                                  elide: Text.ElideRight
                              }
              
                              background: Rectangle {
                                  implicitWidth: 90
                                  implicitHeight: 30
                                  opacity: enabled ? 1 : 0.3
                                  border.color: pressed ? "blue" : "chartreuse"
                                  border.width: 1
                                  radius: 4
                              }
                  }
              
              
                Evgenii Legotckoi
                • Шілде 1, 2019, 3:50 Т.Қ.
                • (өңделген)

                Я Вам написал, что вы используете control.down , который был в первой версии контролов, при этом этот код у вас для второй версии контролов. Вы намешали две версии библиотек, которые несовместимы.

                я поменял в вашем случае

                border.color: control.down ? "blue" : "chartreuse"
                

                На

                border.color: pressed ? "blue" : "chartreuse"
                

                Возможно, кнопка у вас белая потому, что вы используете opacity параметр, который отвечает за прозрачность и делает кнопку белёсой. Покажите изображение, а то по ходу мы с вами о разных вещах говорим.

                  Михаиллл
                  • Шілде 1, 2019, 6:05 Т.Қ.

                  Вот скрин: слева белая, а с права обычная.

                    Evgenii Legotckoi
                    • Шілде 2, 2019, 1:29 Т.Қ.

                    Вот рабочий пример

                    import QtQuick 2.12
                    import QtQuick.Window 2.12
                    import QtQuick.Controls 2.12
                    
                    Window {
                        visible: true
                        width: 640
                        height: 480
                        title: qsTr("Hello World")
                    
                        Button {
                            id: page0Button0
                            y: parent.height * 0.16
                            width: parent.width * 0.3
                            height: parent.height * 0.08
                            text: qsTr("1 of 2 colors") //"1 из 2 цветов"
                            anchors.left: parent.left
                            anchors.leftMargin: parent.width * 0.14
                            contentItem: Text {
                                        text: page0Button0.text
                                        font: page0Button0.font
                                        opacity: enabled ? 1.0 : 0.3
                                        color: page0Button0.pressed ? "red" : "black"
                                        horizontalAlignment: Text.AlignHCenter
                                        verticalAlignment: Text.AlignVCenter
                                        elide: Text.ElideRight
                                    }
                    
                                    background: Rectangle {
                                        implicitWidth: 90
                                        implicitHeight: 30
                                        opacity: enabled ? 1 : 0.3
                                        border.color: page0Button0.pressed ? "blue" : "chartreuse"
                                        border.width: 1
                                        radius: 4
                                    }
                        }
                    }
                    
                      Михаиллл
                      • Шілде 2, 2019, 4:48 Т.Қ.

                      Спасибо, а если дописать так, то еще и фон меняется

                          Button {
                              id: page0Button0
                              y: parent.height * 0.16
                              width: parent.width * 0.3
                              height: parent.height * 0.08
                              text: qsTr("1 of 2 colors") //"1 из 2 цветов"
                              anchors.left: parent.left
                              anchors.leftMargin: parent.width * 0.14
                              //autoRepeat: false
                              //display: AbstractButton.TextBesideIcon
                      
                              contentItem: Text {
                                                 text: page0Button0.text
                                                 font: page0Button0.font
                                                 opacity: enabled ? 1.0 : 0.3
                                                 color: page0Button0.pressed ? "red" : "black"
                                                 horizontalAlignment: Text.AlignHCenter
                                                 verticalAlignment: Text.AlignVCenter
                                                 elide: Text.ElideRight
                                             }
                      
                                             background: Rectangle {
                                                 implicitWidth: 90
                                                 implicitHeight: 30
                                                 opacity: enabled ? 1 : 0.3
                                                 border.color: page0Button0.pressed ? "blue" : "black"
                                                 color: page0Button0.pressed ? "#d3ffe5" : "#e4e4ff"
                                                 border.width: 1
                                                 radius: 4
                                             }
                          }
                      

                        Пікірлер

                        Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
                        Кіріңіз немесе Тіркеліңіз