BlinCT
BlinCT27. April 2020 04:14

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

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

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

5
BlinCT
  • 27. April 2020 14:47
  • Die Antwort wurde als Lösung markiert.

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

    Evgenii Legotckoi
    • 28. April 2020 02:52

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

      R
      • 30. April 2020 03:56

      якщо потрібно просто кнопку то можна створити файли 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
        • 30. April 2020 04:37

        і другий варіант це через власний стиль
        одразу коротке пояснення в файлах вказано значення типу 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
          • 30. April 2020 04:53

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

          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"
              }
          }
          

            Kommentare

            Nur autorisierte Benutzer können Kommentare posten.
            Bitte Anmelden oder Registrieren
            Letzte Kommentare
            A
            ALO1ZE19. Oktober 2024 08:19
            Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
            ИМ
            Игорь Максимов5. Oktober 2024 07:51
            Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
            d
            dblas55. Juli 2024 11:02
            QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
            k
            kmssr8. Februar 2024 18:43
            Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
            Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
            Jetzt im Forum diskutieren
            J
            JacobFib17. Oktober 2024 03:27
            добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
            JW
            Jhon Wick1. Oktober 2024 15:52
            Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
            КГ
            Кирилл Гусарев27. September 2024 09:09
            Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
            F
            Fynjy22. Juli 2024 04:15
            при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

            Folgen Sie uns in sozialen Netzwerken