BlinCT
BlinCTApril 27, 2020, 4:14 a.m.

Кастомный баттон qml со своими стилями

Всем привет.
Появилась необходимость сделать свою qml кнопку, то есть расширить стандартную из 2 контролов.
Например нужно в оформлении кнопки сделать декорацию вертикальную или горизонтальную.
Если горизонтальная то сверху и снизу на кнопке прочерчиваем 2 прямые на растоянии от границы кнопки например 7 пикселей, и внутри этой декорации меняем цвет например на белый если нажали на кнопку.
Буду очень признателен если кто то накинет примерно код такой кнопки.
Изменение в стиле придется делать много, а исходя из этого я хоть разберу как это работает. Особенно в дизайне.
Спасибо.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

5
BlinCT
  • April 27, 2020, 2:47 p.m.
  • The answer was marked as a solution.

Вопрос закрыт, нашел пример в инете)

    Evgenii Legotckoi
    • April 28, 2020, 2:52 a.m.

    Скинул бы тогда хоть пример кода сюда, а то как обычно

      R
      • April 30, 2020, 3:56 a.m.

      якщо потрібно просто кнопку то можна створити файли MyButton.qml з кодом і використовувати як зазвичай

      import QtQuick 2.7
      import QtQuick.Controls 1.4
      import QtQuick.Layouts 1.3
      import QtQuick.Controls.Styles 1.4
      
      Button {
      
          id: but
          property string text;
          property alias checkable: but.checkable
          property bool visibleBackground: true
          style: ButtonStyle {
              background:  Item {
                  Rectangle {
                      anchors.fill: parent
                      anchors.bottomMargin: control.pressed ? 0 : -1
                      color: "#10000000"
                      //radius: baserect.radius
                  }
                  Rectangle {
                      id: baserect
                      gradient: Gradient {
                          GradientStop {color: control.pressed ? styleUser.value("ButtonGradientColor2") : styleUser.value("ButtonGradientColor1") ; position: 0}
                          GradientStop {color: control.pressed ? styleUser.value("ButtonGradientColor1") : styleUser.value("ButtonGradientColor2") ; position: control.pressed ? 0.1: 1}
                      }
                      radius: 0
                      visible: but.visibleBackground
                      anchors.fill: parent
                      border.color: control.activeFocus ? styleUser.value("ButtonBorderColor") : styleUser.value("ButtonBorderActiveFocusColor")
                      Rectangle {
                          anchors.fill: parent
                          //radius: parent.radius
                          color: control.activeFocus ? "#47b" : styleUser.value("ButtonActiveFocus")
                          opacity: control.hovered || control.activeFocus ? 0.1 : 0
                          Behavior on opacity {NumberAnimation{ duration: 100 }}
                      }
                      Rectangle {
                          anchors.fill: parent
                          color: "#d4d4d4"
                          opacity: control.enabled ? 0 : 0.3
      
                      }
                  }
                  Image {
                      id: imageItem
                      visible: control.menu !== null
                      source: styleUser.urlStyle() + "arrow-down.png"
                      anchors.verticalCenter: parent.verticalCenter
                      anchors.right: parent.right
                      anchors.rightMargin: padding.right
                      opacity: control.enabled ? 0.6 : 0.5
                  }
              }
              label: Text {
                  text: but.text
                  horizontalAlignment: Text.AlignHCenter
                  verticalAlignment: Text.AlignVCenter
                  color: styleUser.value("ButtonTextColor")
              }
      
      
          }
      }
      
        R
        • April 30, 2020, 4:37 a.m.

        і другий варіант це через власний стиль
        одразу коротке пояснення в файлах вказано значення типу styleUser.value("ButtonActiveFocus") це тому що в нас дані стилю беруться з файлу і просто не хотілось переписувати, так як код з проекту взятий

        для цього потрідно в main.cpp додати

            QQuickStyle::setStyle(":/MyStyle");
            QQuickStyle::setFallbackStyle("Default");
        

        створити файл qtquickcontrols2.conf

        [Controls]
        Style=MyStyle
        
        [Material]
        Primary=#41cd52
        Accent=#41cd52
        Theme=System
        

        далі в папці потрібно створити папку MyStyle
        в які будуть файли стилю на різні компоненти в тому числі і Button.qml (можна взяти їх перекопіювати з базових стилів)

        import QtQuick 2.12
        import QtQuick.Controls 2.12
        import QtQuick.Controls.impl 2.12
        import QtQuick.Templates 2.12 as T
        
        T.Button {
            id: control
        
            contentItem: Label {
                text: control.text
                horizontalAlignment: Text.AlignHCenter
                verticalAlignment: Text.AlignVCenter
                color: styleUser.value("ButtonTextColor")
            }
        
            background:  Item {
                Rectangle {
                    anchors.fill: parent
                    anchors.bottomMargin: control.pressed ? 0 : -1
                    color: "#10000000"
                    //radius: baserect.radius
                }
                Rectangle {
                    id: baserect
                    gradient: Gradient {
                        GradientStop {color: control.pressed ? styleUser.value("ButtonGradientColor2") : styleUser.value("ButtonGradientColor1") ; position: 0}
                        GradientStop {color: control.pressed ? styleUser.value("ButtonGradientColor1") : styleUser.value("ButtonGradientColor2") ; position: control.pressed ? 0.1: 1}
                    }
                    radius: 0
                    anchors.fill: parent
                    border.color: control.activeFocus ? styleUser.value("ButtonBorderColor") : styleUser.value("ButtonBorderActiveFocusColor")
                    Rectangle {
                        anchors.fill: parent
                        //radius: parent.radius
                        color: control.activeFocus ? "#47b" : styleUser.value("ButtonActiveFocus")
                        opacity: control.hovered || control.activeFocus ? 0.1 : 0
                        Behavior on opacity {NumberAnimation{ duration: 100 }}
                    }
                    Rectangle {
                        anchors.fill: parent
                        //radius: parent.radius
                        //color: control.enabled ? "#47b" : styleUser.value("ButtonActiveFocus")
                        color: "#d4d4d4"
                        opacity: control.enabled ? 0 : 0.3
                       // Behavior on opacity {NumberAnimation{ duration: 100 }}
                    }
                }
            }
        }
        
        
          BlinCT
          • April 30, 2020, 4:53 a.m.

          Сорян, забыл кинуть то что примерно хотел получить в реализации

          Button
          {
              id: control
              text: qsTr("Button")
          
              property string label: ""
              property alias rectWidth: rectSize.implicitWidth
              property alias rectHeight: rectSize.implicitHeight
          
              contentItem: Text {
                  text: control.label
                  font: control.font
                  opacity: enabled ? 1.0 : 0.3
                  color: control.down ? "#FA8072" : "#000000"
                  horizontalAlignment: Text.AlignHCenter
                  verticalAlignment: Text.AlignVCenter
                  elide: Text.ElideRight
              }
          
              background: Rectangle {
                  id: rectSize
                  implicitWidth: 100
                  implicitHeight: 96
          //        opacity: enabled ? 1 : 0.3
          //        anchors.fill: parent
                  color: "#666666"
          //        border.color: control.down ? "#FA8072" : "#696969"
                  border.width: 1
          //        radius: 4
              }
          
              Rectangle
              {
                  id: rectUp
          
                  anchors.top: parent.top
                  anchors.left: parent.left
                  anchors.right: parent.right
          
                  height: 10
          
                  color: "#101010"
              }
          
              Rectangle
              {
                  id: rectDown
          
                  anchors.bottom: parent.bottom
                  anchors.left: parent.left
                  anchors.right: parent.right
          
                  height: 10
          
                  color: "#222222"
              }
          }
          

            Comments

            Only authorized users can post comments.
            Please, Log in or Sign up
            d
            • dsfs
            • April 26, 2024, 2:35 p.m.

            C++ - Test 001. The first program and data types

            • Result:73points,
            • Rating points1
            d
            • dsfs
            • April 26, 2024, 2:29 p.m.

            Qt - Test 001. Signals and slots

            • Result:63points,
            • Rating points-1
            SH

            C++ - Test 001. The first program and data types

            • Result:33points,
            • Rating points-10
            Last comments
            k
            kmssrFeb. 9, 2024, 5:43 a.m.
            Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
            Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
            EVA
            EVADec. 25, 2023, 9:30 p.m.
            Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
            J
            JonnyJoDec. 25, 2023, 7:38 p.m.
            Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
            G
            GvozdikDec. 19, 2023, 8:01 a.m.
            Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
            Now discuss on the forum
            G
            GarApril 22, 2024, 3:46 p.m.
            Clipboard Как скопировать окно целиком в clipb?
            DA
            Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
            Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
            a
            a_vlasovApril 14, 2024, 4:41 p.m.
            Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
            Павел Дорофеев
            Павел ДорофеевApril 14, 2024, 12:35 p.m.
            QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
            f
            fastrexApril 4, 2024, 2:47 p.m.
            Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

            Follow us in social networks