Qt android qml кнопка назад

Qt/QML/Android(navigation button)

Можно обрабатывать back кнопку так как работает кнопка home? Если можно то как?? Это нужно обрабатываться через JNI? Буду благодарен за любую помощь.

We recommend hosting TIMEWEB

Subscribers

  • Evgenij Legotskoj
  • #
  • Feb. 12, 2019, 12:40 p.m.
  • The answer was marked as a solution.

Нет, JNI тут не потребуется, по моему мнению.

Ну вот один возможный вариант

Когда мы пишем event.accepted = true это значит шо твоя application на закрывается а дальше работает на foreground, но мой вопрос в другом можно чтоб кнопка назад не убивала application, а сделала minimize??

но мой вопрос в другом можно чтоб кнопка назад не убивала application, а сделала minimize??

Вам следовало бы сразу соответствующим образом сформулировать вопрос. Разработчики приложения в итоге решают, как поступать и дефолтное поведение может быть переопределено. Есть приложения в которых вообще происходит logout клиента и ничего больше.

Думаю, что тут уже нужно копать в сторону JNI, с фоновой работой всё обстоит несколько сложнее. Требуются настройки AndroidManifest. Здесь не подскажу.

Источник

QML — Урок 002. Custom Button in QML Android

Начну серию уроков по QML Android с кастомизации кнопки, или правильнее сказать со стилизации , поскольку в данном случае такой термин подходит больше. Мы не будем вызывать диалоговые окна в данном уроке, а просто сделаем свой QML Cutom Button , который будет менять цвет при нажатии на него. А для наглядности таких кнопок будет две.

Первая кнопка будет красного цвета с черным ободком и чёрным текстом, а при нажатии она будет менять цвет фона на черный с красным ободком и красным цветом. А вторая кнопка будет иметь те же цвета, но в противоположной последовательности.

Структура проекта QML Custom Button

Проект создаётся в QtCreator как проект приложения Qt Quick с элементами Quick Controls. Фактически там уже будет менюбар, несколько диалогов и пара кнопок. Так вот, выкидываем всё, кроме двух кнопок и поехали их кастомизировать.

А структура проекта в данном случае получится следующая:

  • QMLCutomButton.pro — Знакомый нам профайл проекта;
  • deployment.pri — файл для установки исходного кода на устройство;
  • main.cpp — давно знакомый стартовый файл приложения
  • qml.qrc — файл ресурсов проекта, там и складируются qml файлы
  • main.qml — файл qml главного окна приложения
  • MainForm.ui.qml — и опять ресурсный файл дизайнера, да простят меня хардкорщики. В нём и будут прятаться кнопки. Проект создавался под минимальную версию Qt 5.5.

QMLCustomButton.pro

Поскольку это первый урок по данной теме, то приведу листинг данного файла.

deployment.pri

А также и этот файл до кучу, хоть он и создаётся по умолчанию.

Читайте также:  Взлом wep с андроида

main.cpp

В данном файле необходимо создать движок для QML и загрузить исходный файл в него.

MainForm.ui.qml

QtCreator предупреждает, что данный файл можно редактировать только в дизайнере, но на самом деле это не так. Но мы не будем редактировать его вручную.

main.qml

А теперь посмотрим на то, ради чего всё затевалось, а именно логика работы кнопок, которая была описана в самом начале статьи. Для стилизации кнопок используется настройка style , в которой определяется ButtonStyle . Тело нашего Custom Button — это прямоугольник Rectangle , выступающий в роли background кнопки. Для этого Rectangle Задаётся его цвет и обводка с закруглением углов. А чтобы кастомизировать текст, необходимо Button Style переопределить label кнопки, указав цвет текста.

Заметьте также, что указание цвета производится через условное выражение посредством проверки объекта control , который указывает на виджет, то есть кнопку, которая контролирует данный стиль. И если этот control нажат, то цвет один, в противном случае другой.

Однозначно, меня порадовало то, что имеется возможность без всяких эмуляторов и установки на Android Device посмотреть результат проделанной работы, а это очень вдохновляет. Да и кроссплатформенность не может не радовать.

А внешний вид получившихся кнопок будет такой как на ниже представленных скриншотах для Декстопа и со смартфона Meizu M1 Note . Также посмотреть на логику работы приложения можно в видеоуроке, который идёт после скриншотов.

Видеоурок

Рекомендуем хостинг TIMEWEB

Рекомендуемые статьи по этой тематике

Источник

Qt/QML/Android(navigation button)

Можно обрабатывать back кнопку так как работает кнопка home? Если можно то как?? Это нужно обрабатываться через JNI? Буду благодарен за любую помощь.

Рекомендуем хостинг TIMEWEB

Подписчики

  • Евгений Легоцкой
  • #
  • 12 февраля 2019 г. 12:40
  • Ответ был помечен как решение.

Нет, JNI тут не потребуется, по моему мнению.

Ну вот один возможный вариант

Когда мы пишем event.accepted = true это значит шо твоя application на закрывается а дальше работает на foreground, но мой вопрос в другом можно чтоб кнопка назад не убивала application, а сделала minimize??

но мой вопрос в другом можно чтоб кнопка назад не убивала application, а сделала minimize??

Вам следовало бы сразу соответствующим образом сформулировать вопрос. Разработчики приложения в итоге решают, как поступать и дефолтное поведение может быть переопределено. Есть приложения в которых вообще происходит logout клиента и ничего больше.

Думаю, что тут уже нужно копать в сторону JNI, с фоновой работой всё обстоит несколько сложнее. Требуются настройки AndroidManifest. Здесь не подскажу.

Источник

Qt android qml кнопка назад

I’m making simple examples with Qt 5.1 for android, but i have noted that with the backbutton the app exit instead of come back at previous stack page. Will be it also in future version? I think that is very important to have native behaviour (without trick).

Читайте также:  Файл backup для android

I think 5.1 is more like a beta suport for android. Some essential stuff like camera and full sensor support is missing (some are working though).
I guess Qt5.2 will be awesome

This is true, but I’ll tell you alpha version 4.1 was better than qt5.1 for android, was more stable

Hi there. The back button functionality works nicely in the Qt 5.1 developer preview without need for any tricks and behaves «according to specification»:http://developer.android.com/reference/android/app/Activity.html (scroll to onKeyDown method).

According to Android documentation, the back button event is delivered via Activity.onKeyUp() which is translated as QEvent::KeyRelease with key code Qt::Key_Back.

To prevent your app from quitting, you have to handle (accept) this event. For example, in QML you would do something like this:

@
Rectangle <
focus: true // important — otherwise we’ll get no key events

If you want to handle it on C++ level, override keyReleaseEvent() of your main Window and do the same in there.

That being said, how you implement the «come back at previous stack page» is entirely up to you.

Thanks for explaining 🙂 It is a bit odd that it somehow works its way to quit.

I managed to catch the android back button in QML:

@ApplicationWindow <
onClosing: <
close.accepted = false
if (contextMenuManager.menuVisible)
contextMenuManager.menuVisible = false
>
>@

Keys.onReleased catches the Android back button in some instances.

It doesn’t seem to work with ListView though. focus must be directed somewhere where I haven’t anticipated.

Here is a sample main.qml with a ListView, which does not catch the Android back button:
@
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1

ApplicationWindow <
id: appWindow
visible: true
width: 640
height: 480
title: qsTr(«Hello World»)

Keys.onReleased catches the Android back button in some instances.

It doesn’t seem to work with ListView though. focus must be directed somewhere where I haven’t anticipated.

Here is a sample main.qml with a ListView, which does not catch the Android back button:
@
import QtQuick 2.3
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1

ApplicationWindow <
id: appWindow
visible: true
width: 640
height: 480
title: qsTr(«Hello World»)

Can someone post a C++ version of this? I have tried to convert it and I am still not seeing the back key.

Never mind. Here is a C++ version I was able to get to work.

// regular MainWindow stuff.

void MainWindow::keyPressEvent (QKeyEvent* event) <

if (event->key () == Qt::Key_Back)
qDebug () > » key () == Qt::Key_HomePage)
qDebug () > » key () == Qt::Key_Menu)
qDebug () > » key () == Qt::Key_unknown)
qDebug () > » accept ();
>
@

Can someone post a C++ version of this? I have tried to convert it and I am still not seeing the back key.

Never mind. Here is a C++ version I was able to get to work.

Читайте также:  Маджонг артефакт для андроида

// regular MainWindow stuff.

void MainWindow::keyPressEvent (QKeyEvent* event) <

if (event->key () == Qt::Key_Back)
qDebug () > » key () == Qt::Key_HomePage)
qDebug () > » key () == Qt::Key_Menu)
qDebug () > » key () == Qt::Key_unknown)
qDebug () > » accept ();
>
@

on Android, I did this:

I get a debug message for the back button, but not for the menu button. I also tried Qt::Key_TopMenu, but still nothing

nor do I get the «some other button» debug message when the menu button is pressed, so this method is not even being called when I press the menu button

this message must be handled somewhere else

can anyone help?

In Qt 5.4.2 this is what i use and it works fine:

ApplicationWindow <
.
onClosing: <
if (Qt.platform.os == «android») <
close.accepted = false;
if (stack.depth > 1) stack.pop();
>
>
>

C++ code. Gives the desired/standard effect on Android. Use a QWidget with a QStackedLayout in the main window.

Override the closeEvent in the header:

Implement the code in the body:

void MainWindow::closeEvent(QCloseEvent *event) <

Источник

Qt Documentation

Contents

Push-button that can be clicked to perform a command or answer a question. More.

Properties

Detailed Description

Button presents a push-button control that can be pushed or clicked by the user. Buttons are normally used to perform an action, or to answer a question. Typical buttons are OK, Apply, Cancel, Close, Yes, No, and Help.

Button inherits its API from AbstractButton. For instance, you can set text, display an icon, and react to clicks using the AbstractButton API.

A button emits the signal clicked() when it is activated by the user. Connect to this signal to perform the button’s action. Buttons also provide the signals canceled(), doubleClicked(), pressed(), released() and pressAndHold() for long presses.

See the snippet below on how to connect to the button’s signals.

Property Documentation

This property holds whether the button is flat.

A flat button typically does not draw a background unless it is pressed or checked.

The default value is false .

This property holds whether the button is highlighted.

A button can be highlighted in order to draw the user’s attention towards it. It has no effect on keyboard interaction.

The default value is false .

В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Источник

Оцените статью
Import Statement: import QtQuick.Controls 2.15
Since: Qt 5.7
Inherits: