Qt как сделать всплывающее окно

Обновлено: 03.05.2024

По факту, это будет тот самый момент, когда дополнительных различий в коде практически не будет. В обоих случаях имеются соответствующие Классы/Типы, которые отвечаю за весь данный функционал.

Вывод в консоль

В случае с Java для этого служит класс Log, а в случае с QML для этого служит функционал console, который хорошо знаком Web-программистам.

В случае с Java это будут следующие статические методы класса Log:

В случае с Qt QML это будут методы console:

  • console.log
  • console.debug
  • console.info
  • console.warn
  • console.error

Функционал console использует методы C++ qCDebug, qCWarning и т.д. То есть в рамках QML данные функции пришедшие из JavaScript транслируются в C++ методы, которые уже и служат для вывода информации в консоль.

Для вывод в консоль в Java потребуется импортировать в java файл соответствующий пакет с классом Log

И вызвать необходимый методы данного класса

Для вывода в консоль из QML кода не требуется ничего подключать или импортировать. Нужно только вызвать необходимую функцию в нужном месте кода.

Но в данном уроке постараемся реализовать стандартный Toast, который присутствует в Java Android.

Данный Toast в Java Android выглядел у меня так


Тогда как Toast в QML выглядел так


Для Java нужно импортировать класс Toast

Получилось мало кода, и в данном уроке Java несколько выигрывает по объёму написанного кода, поскольку в QML мы постараемся приблизить внешний вид и поведение ToolTip QML к внешнему виду и поведению Toast в Java, а это уже потребует некоторой кастомизации.

Для использования типа ToolTip импортируется модуль QtQuick.Controls 2

Далее нужно добавить в главное окно приложения сам ToolTip, дать ему id и кастомизировать его.

А потом уже установить ему текст и установить свойство visible на true.

Заключение

Вывод в консоль равнозначен между Java и Qt QML.

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

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

Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Functionality of the standard notification system tray at times can be insufficient for the implementation of ambitious pans for styling applications. We therefore consider the embodiment of pop-up messages in the style of PopUp DE Gnome notification, namely, as shown in the following figure.


PopUp notification Gnome style

To demonstrate the notification I propose to create an application, which will be a field for entering text, and a button by pressing which will be called a pop-up message.

The message will be displayed in the lower right corner of the tray system tray. This notice must be sure to scale the contents.

Fade-in it will be implemented within 150 milliseconds and the disappearance, after three seconds.

  1. 1. Project structure
  2. 2. PopupWindow.pro и mainwindow.ui
  3. 3. mainwindow.h
  4. 4. mainwindow.cpp
  5. 5. popup.h
  6. 6. popup.cpp
  7. 7. Result
  8. 8. Video

Project structure

  • PopupWindow.pro - the profile of the project;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - file source code of the main application window;
  • mainwindow.ui - form the main application window;
  • main.cpp - start file the application source code;
  • popup.h - header file notifications;
  • popup.cpp - file source pop-up message.

PopupWindow.pro и mainwindow.ui

The profile of the project, do not connect anything special, but in the main application window, just put a button and a text entry field.

mainwindow.h

The header of the main window of the application you must include the header file PopUp notification and declare the notification object itself, and there will be declared a slot for processing pressing the start button a pop-up notification. This slot will be installed in the text notification and position change notifications on the computer screen in the notification size.

mainwindow.cpp

popup.h

In order to prepare the notification must be inherited from QWidget class that you want to disable window decoration, and put a transparent background. You also need to set it up so that a notice was always on top of all windows. Rendering translucent background notification will be made in the method paintEvent() , in which the full width and height of the notification widget is drawn semi-transparent black rectangle with rounded edges.

Animation appearance and disappearance of the notification will be made through QPropertyAnimation object.

What is important: fitting the size of the widget should be made at the time the text in the notification, and not during the redrawing or installation location notifications on the screen, or to be received is not correct size and magnitude of the notice, it will not in the expected location, or not with the expected size.

To implement time-limited display notifications on the screen applies QTimer .

popup.cpp

Result

Archive of the source: PopupWindow

As a result, the message will be as follows:


Video

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.


PopUp уведомление в стиле Gnome

Будет реализовано плавное появление в течении 150 миллисекунд и исчезновение, через три секунды.

  1. 1. Структура проекта
  2. 2. PopupWindow.pro и mainwindow.ui
  3. 3. mainwindow.h
  4. 4. mainwindow.cpp
  5. 5. popup.h
  6. 6. popup.cpp
  7. 7. Результат
  8. 8. Видеоурок

Структура проекта

PopupWindow.pro и mainwindow.ui

В профайле проекта не подключаем ничего особенного, а в главном окне приложения просто помещаем кнопку и поле для ввода текста.

mainwindow.h

В заголовочном файле главного окна приложения необходимо подключить заголовочный файл PopUp уведомления и объявить сам объект уведомления, а также там будет объявлен слот для обработки нажатия на кнопку запуска всплывающего уведомления. В данном слоте будет производиться установка текста в уведомление и изменение положения уведомления на экране компьютера в соответствии с размерами уведомления.

mainwindow.cpp

popup.h

Для разработки уведомления необходимо наследоваться от класса QWidget, у которого необходимо отключить оформление окна, и выставить прозрачный фон. Также необходимо настроить его так, чтобы уведомление всегда находилось поверх все окон. Отрисовка полупрозрачного фона уведомления будет производиться в методе paintEvent(), в котором на всю ширину и высоту виджета уведомления будет нарисован полупрозрачный прямоугольник чёрного цвета с закруглённым краями.

Анимация появления и исчезновения уведомления будет производиться посредством объекта QPropertyAnimation.

Что важно: подгонка размеров виджета должна производиться в момент установки текста в уведомление, а не во время перерисовки или установки местоположения уведомления на экране, иначе будут получены не верный величины размеров уведомления и оно окажется не в ожидаемом месте или не с ожидаемыми размерами.

Для реализации ограниченного по времени показа уведомления на экране компьютера применим QTimer .

popup.cpp

Результат

Архив с исходниками: PopupWindow


Видеоурок

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

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

Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Each type of popup control has its own specific target use case. The following sections offer guidelines for choosing the appropriate type of popup control, depending on the use case.

Drawer Control


Drawer provides a swipe-based side panel, similar to those often used in touch interfaces to provide a central location for navigation.

The drawer can be positioned at any of the four edges of the screen. It allows the user to add navigation without taking up valuable screen space. The user can show and hide the drawer at any time with a simple swipe movement.

Menu Control


The Menu control displays a vertical list of items that can be selected. It can be used for offering a list of actions that can be taken in a given context.

Popup Control


A Popup displays content over other application content. It prompts the user to make a decision or enter information.

Popups can be modal or non-modal. A modal popup blocks users from interacting with the application until they have made a choice and closed the popup.

A popup can be used for:

  • communicating a message to the user that they must read and acknowledge.
  • displaying an error message.
  • prompting the user to make a choice and/or enter a value.

ToolTip Control


ToolTip shows a short piece of text that informs the user of a control's function. It is typically placed above or below the parent control.

  • Use a tooltip if a control has little or no descriptive text, or needs a short explanation.
  • Use a tooltip only if the information on a particular control is not available elsewhere in the screen.
  • Keep the tooltip text short so that it does not cover other content while being displayed.

Related Information

© 2022 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.

Popup is the base type of popup-like user interface controls. It can be used with Window or ApplicationWindow.

In order to ensure that a popup is displayed above other items in the scene, it is recommended to use ApplicationWindow. ApplicationWindow also provides background dimming effects.

Popup does not provide a layout of its own, but requires you to position its contents, for instance by creating a RowLayout or a ColumnLayout.

Items declared as children of a Popup are automatically parented to the Popups's contentItem. Items created dynamically need to be explicitly parented to the contentItem.

Popup Layout

The following diagram illustrates the layout of a popup within a window:


The implicitWidth and implicitHeight of a popup are typically based on the implicit sizes of the background and the content item plus any insets and paddings. These properties determine how large the popup will be when no explicit width or height is specified.

The geometry of the contentItem is determined by the padding. The following example reserves 10px padding between the boundaries of the popup and its content:

The background item fills the entire width and height of the popup, unless insets or an explicit size have been given for it.

Negative insets can be used to make the background larger than the popup. The following example uses negative insets to place a shadow outside the popup's boundaries:

Popup Sizing

If only a single item is used within a Popup, it will resize to fit the implicit size of its contained item. This makes it particularly suitable for use together with layouts.

Sometimes there might be two items within the popup:

In this case, Popup cannot calculate a sensible implicit size. Since we're anchoring the PageIndicator over the SwipeView, we can simply set the content size to the view's implicit size:

Popup Positioning

Similar to items in Qt Quick, Popup's x and y coordinates are relative to its parent. This means that opening a popup that is a child of a Button, for example, will cause the popup to be positioned relative to the button.

The following example uses the attached Overlay.overlay property to position a popup in the center of the window, despite the position of the button that opens the popup:

Another way to center a popup in the window regardless of its parent item is to use anchors.centerIn:

To ensure that the popup is positioned within the bounds of the enclosing window, the margins property can be set to a non-negative value.

Popup Transitions

Since Qt 5.15.3 the following properties are restored to their original values from before the enter transition after the exit transition is completed.

This allows the built-in styles to animate on these properties without losing any explicitly defined value.

Читайте также: