Эдуард Неткачёв24. März 2022 14:29
Выделение нескольких объектов
QML, выделение нескольких элементов мышкой
Приветствую всех.
Не могу разобраться как сделать выделение нескольких элементов с помощью удержания клавиши мыши. Уже разные способы пробовал, но каждый раз какой-то затык.
Вот кусок основной программы main.qml:
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.5 ApplicationWindow { visible: true title: qsTr("Selection and Scaling") width: Screen.desktopAvailableWidth*50/100 height: Screen.desktopAvailableHeight*80/100 color: "whitesmoke" property double my_scale: 1.0 Flickable { id: _scrollSetup anchors.fill: parent boundsMovement: Flickable.StopAtBounds // если контент больше видимой области, то при перемещении контента он останавливается на границе контента с видимой областью contentWidth: _сolumn.width*my_scale >parent.width ? (_сolumn.width*my_scale):parent.width contentHeight: _сolumn.height*my_scale >parent.height ? (_сolumn.height*my_scale):parent.height MouseArea { id: _mouseFlickable anchors.fill: parent property point clickPos: "0,0" onWheel: if (wheel.angleDelta.y>0) { my_scale*=1.05; } else { my_scale*=0.95; } // реакция на скролл onClicked: console.log("_mouseFlickable.onClicked"); onPressed: { console.log("_mouseFlickable.onPressed"); clickPos = Qt.point(mouse.x,mouse.y) _rect_select.x=clickPos.x; _rect_select.y=clickPos.y; _rect_select.width=0; _rect_select.height=0; _rect_select.visible=true; } onReleased: { console.log("_mouseFlickable.onReleased"); _rect_select.visible=false; } onEntered: console.log("_mouseFlickable.onEntered"); onExited: console.log("_mouseFlickable.onExited"); onPositionChanged: { _rect_select.x=Math.min(mouse.x,clickPos.x) _rect_select.y=Math.min(mouse.y,clickPos.y) _rect_select.width=Math.abs(clickPos.x-mouse.x) _rect_select.height=Math.abs(clickPos.y-mouse.y) } Column { id: _сolumn anchors.verticalCenter: parent.verticalCenter anchors.horizontalCenter: parent.horizontalCenter scale: my_scale Row { id: _rowUpper MyElement { id: element_1 number: 1 height: 160 width: 160 } MyElement { id: element_2 number: 2 height: 160 width: 160 } MyElement { id: element_3 number: 3 height: 160 width: 160 } MyElement { id: element_4 number: 4 height: 160 width: 160 } } Rectangle { anchors.horizontalCenter: parent.horizontalCenter height: 4 color: "lightsteelblue" width: parent.width } Row { id: _rowLower MyElement { id: element_5 number: 5 height: 160 width: 160 } MyElement { id: element_6 number: 6 height: 160 width: 160 } MyElement { id: element_7 number: 7 height: 160 width: 160 } MyElement { id: element_8 number: 8 height: 160 width: 160 } } } } } Rectangle { id: _rect_select visible: false color: "blue" opacity : 0.3 } }
Вот код элемента MyElement.qml:
import QtQuick 2.0 Item { property int number: 0 property bool select: false MouseArea { id: _mouseArea anchors.fill: parent hoverEnabled: true // это для работы функции containsMouse (наведение курсора мыши на область) propagateComposedEvents: true onClicked: { console.log("_mouse_" + number + ".onClicked"); mouse.accepted = false; } onPressed: { console.log("_mouse_" + number + ".onPressed"); mouse.accepted = false; } onReleased:{ console.log("_mouse_" + number + ".onReleased"); mouse.accepted = false; } onEntered: { console.log("_mouse_" + number + ".onEntered"); } onExited: { console.log("_mouse_" + number + ".onExited"); } Rectangle { id: _rect anchors.fill: parent color: "green" scale: select ? 1.0 : _mouseArea.containsMouse ? 0.95 : 0.90 } } }
Может есть мысли как это сделать.
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.Magst du es? In sozialen Netzwerken teilen!
Kommentare
sf
- sdfsdfkp fgskpgokspdog
- 14. Oktober 2024 15:09
C++ - Тест 004. Указатели, Массивы и Циклы
- Ergebnis:90punkte,
- Bewertungspunkte8
МВ
- Максим Васильев
- 2. Oktober 2024 04:14
Qt - Тест 001. Сигналы и слоты
- Ergebnis:68punkte,
- Bewertungspunkte-1
ЛС
- Лев Семенов
- 30. September 2024 11:04
C++ - Тест 001. Первая программа и типы данных
- Ergebnis:53punkte,
- Bewertungspunkte-4
Letzte Kommentare
ИМ
Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
Игорь Максимов5. Oktober 2024 07:51
QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5. Februar 2024 01:50
EVA25. Dezember 2023 10:30
Jetzt im Forum diskutieren
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
ИМ
Реализация навигации по разделам Спасибо Евгений!
Игорь Максимов3. Oktober 2024 04:05
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…
КГ
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
Кирилл Гусарев27. September 2024 09:09
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
Как вариант, считать пересечение объектов с прямоугольником выделения,
примерный код набрасал: