Size: a a a

2021 April 21

T

Tamer in Qt
Item {
   id: root

   // Относительно этого азимута происходит доворот кругового сектора
   property real azimuth: 0
   // Относительно этой кнопки будет происходит центрование кнопки
   property var center: centerButton
   // Переменная отвечает за количество кнопок для текущего Popup'a
   property int countButtons
   // Переменная отвечает за текущую кнопку, на которую наведена мышь
   property int currentButtonIndex
   // Выставляется в true, если мышь наведена кнопку "закрытия"
   property bool hovered: false
   // Флаг, отвечающий за запоминание предыдущей кнопки
   property bool checkedPreviousButton: false

   function updatePopup(mouse) {
       const coord = root.mapFromGlobal(mouse.x, mouse.y)

       root._setCurrentButtonIndexIndex(root.childAt(coord.x, coord.y))
       root._setAzimuth(Qt.point(centerButton.width / 2, centerButton.height / 2),
                        Qt.point(coord.x, coord.y))
       canvasRepeat.requestPaint()
   }
   function _setCurrentButtonIndexIndex(item) {
       if (!root.checkedPreviousButton)
           root.hovered = false

       if (item !== null && item instanceof PopupButton
               && typeof item.buttonIndex !== "undefined") {
           root.currentButtonIndex = item.buttonIndex
           return
       } else if (item !== null && item instanceof Rectangle) {
           root.hovered = true
           return
       }

       if (!root.checkedPreviousButton)
           root.currentButtonIndex = -1

   }
   function _setAzimuth(from, to) {
       const dy = to.y - from.y
       const dx = to.x - from.x

       root.azimuth = Math.atan2(dy, dx) - (360 / root.countButtons / 2) / 180 * Math.PI
   }

   Rectangle {
       id: centerButton
       width: 32
       height: 32
       radius: centerButton.width / 2
       color: "#4B4B5E"

       // Canvas занимается отрисовкой кругового сектора (показывает текущее направление к мыши)
       Canvas {
           id: canvasRepeat
           width: parent.width
           height: parent.height
           z: parent.z + 1
           anchors.centerIn: centerButton
           onPaint: {
               const angle = 360 / root.countButtons

               var ctx = getContext("2d");
               ctx.reset()
               ctx.beginPath();
               ctx.arc(centerButton.width / 2, centerButton.height / 2,
                       centerButton.radius - 1, 0 + root.azimuth,
                       angle * Math.PI / 180 + root.azimuth)
               ctx.lineWidth = 2
               ctx.strokeStyle = "#5F8C6D"
               ctx.stroke()
           }
       }
       Rectangle {
           id: closeButton
           width: 28
           height: 28
           color: root.hovered ? "#303256" : "#25263C"
           anchors.centerIn: centerButton
           radius: closeButton.width / 2

           Image {
               id: crossImage
               anchors.centerIn: closeButton
               source: "qrc:/images/cross.svg"
           }
           MouseArea {
               id: closeButtonMouseArea
               anchors.fill: parent
               hoverEnabled: true
           }
       }
   }
}
источник

T

Tamer in Qt
делал ранее меню аля "как в симс"
источник

T

Tamer in Qt
прокинь количество точек для себя, ну и дизайн переработай
источник

Ш

Шерзод in Qt
так сейчас посмотрю
источник

T

Tamer in Qt
канвас в твоём случае будет рисовать не круговой сектор а точки
источник

Ш

Шерзод in Qt
Спасибо)
источник

T

Tamer in Qt
import QtQuick 2.0

Rectangle {
   id: element
   width: 100
   height: 30
   radius: 5
   color: element.currentButtonIndex === element.buttonIndex ? "#73A081" : "#37384C"

   // WARN: Необходимо самим явно задавать индекс кнопки, чтобы добавить в Popup
   property int buttonIndex: 0
   // WARN: Необходимо сделать привязку у родителя (UserTypePopup) к текущему индексу
   property int currentButtonIndex: -1
   // WARN: Необходимо указать количество кнопок, которое будет отображено в Popup
   property int count: 3
   // Задаёт имя кнопки
   property string text
   // Относительно какого элемента центруемся
   property var relativeAlignment

   readonly property real shift: element.count * 15 + relativeAlignment.width / 2
   readonly property real angle: 2 * Math.PI / element.count
                                 * element.buttonIndex
   readonly property real sinForX: Math.sin(element.angle)
   readonly property real cosForY: Math.cos(element.angle)
   readonly property real distance: Math.max(Math.abs(element.sinForX),
                                             Math.abs(element.cosForY))
   readonly property real fractionX:  element.sinForX / element.distance
   readonly property real fractionY: element.cosForY / element.distance

   readonly property real buttonX: element.fractionX * shift
                                   + (element.fractionX - 1) / 2 * element.width
   readonly property real buttonY: element.fractionY * shift
                                   + (element.fractionY - 1) / 2 * element.height

   Text {
       id: elementText
       text: element.text
       color: "white"
       anchors.centerIn: parent
   }

   Component.onCompleted: {
       element.x = buttonX + relativeAlignment.x + relativeAlignment.width / 2
       element.y = buttonY + relativeAlignment.y
   }
}
источник

T

Tamer in Qt
в дополнение
источник

Ш

Шерзод in Qt
ля спасибо)
источник

Ш

Шерзод in Qt
щас посижу поразбираюсь)
источник

A

Alex in Qt
Кто-то сталкивался с проблемами при вызове QDateTime::currentDateTimeUtc или QDateTime::currentDateTime из многих потоков? у меня в дебаге показывает ассёрт из qcalendar.cpp и падает, а если получать дату под мьютексом, то не ассёртит и не падает.
источник

T

Tamer in Qt
Логично, ведь не потокоьезопасный же)
источник

A

Alex in Qt
да где ж логично, если в документации это не описано
источник

A

Alex in Qt
не говоря уже о том, что 6 лет этот код работал без проблем, а на других компах и сейчас работает, это я совершенно случайно поймал на новом компьютере.
источник

A

Alex in Qt
написано, что класс QDateTime reentrant, но это статические методы
источник

T

Tamer in Qt
Ну это тебе не атомарная операция
источник

A

Alex in Qt
ну и что?
источник

A

Alex in Qt
если ему внутри для работы нужен лок, то он внутри реализации и должен быть
источник

D

Dmitriy in Qt
Почему "должен"?
источник

D

Dmitriy in Qt
Это не так уж и логично. Лок не всем требуется
источник