Inserting an image in GUI using QT Designer
I am new to QtDesigner. I wanted to know how to insert an image in the GUI using QT Designer. I am trying to add a logo. Help would be appreciated.
2 Answers 2
You can start inserting a label. Next, you right click on it an then click «change rich text. «. A new window will pop-up. Click on the figure Icon «Insert figure».
Now, you have to create a resource file. Click on the Pencil button. Next, click on the «New resource file» button.
Choose a name and a folder (your working directory would be a good choice) to save it.
Now, click on the «Add prefix» button.
Choose a name for it.
Then, click on the «Add file» button.
And there you go! Click «OK» and you figure should be there. Just be aware that you should resize your figure to a proper size before using it.
Q&A: How do I display an Image in PyQt5/PySide2?
Using QLabel to easily add images to your applications
Adding images to your application is a common requirement, whether you’re building an image/photo viewer, or just want to add some decoration to your GUI. Unfortunately, because of how this is done in Qt, it can be a little bit tricky to work out at first.
In this short tutorial, we will look at how you can insert an external image into your PyQt5/Pyside2 application layout, using both code and Qt Designer.
Which widget to use?
Since you’re wanting to insert an image you might be expecting to use a widget named QImage or similar, but that would make a bit too much sense! QImage is actually Qt’s image object type, which is used to store the actual image data for use within your application. The widget you use to display an image is QLabel .
The primary use of QLabel is of course to add labels to a UI, but it also has the ability to display an image — or pixmap — instead, covering the entire area of the widget. Below we’ll look at how to use QLabel to display a widget in your applications.
Using Qt Designer
First, create a MainWindow object in Qt Designer and add a «Label» to it. You can find Label at in Display Widgets in the bottom of the left hand panel. Drag this onto the QMainWindow to add it.
MainWindow with a single QLabel added
Next, with the Label selected, look in the right hand QLabel properties panel for the pixmap property (scroll down to the blue region). From the property editor dropdown select «Choose File…» and select an image file to insert.
As you can see, the image is inserted, but the image is kept at its original size, cropped to the boundaries of the QLabel box. You need to resize the QLabel to be able to see the entire image.
In the same controls panel, click to enable scaledContents .
When scaledContents is enabled the image is resized to the fit the bounding box of the QLabel widget. This shows the entire image at all times, although it does not respect the aspect ratio of the image if you resize the widget.
Images
The Image component is used for adding images to the UI in several supported formats, including bitmap formats, such as PNG and JPEG, and vector graphics formats, such as SVG. To use any image files in your designs, you need to first add them to Assets:
- Select Assets >
.
- Select the image file, and then select Open.
- Select the location where the image will be saved in the Add Resources dialog.
- Select OK.
Your image is now available in Assets.
When you drag-and-drop an image file from Assets to Navigator or the 2D view, Qt Design Studio automatically creates an instance of the Image component for you with the path to the image file set as the value of the Source field in Properties.
To load images from a URL using a supported URL scheme, specify the URL in the Source field.
You can use the Border Image component to display an image, such as a PNG file, as a border and a background. For more information about using border images to create buttons, see Creating Scalable Buttons and Borders.
If you need to display animated images, such as GIFs, use the Animated Image component.
Image Size
If the image Size is not specified, the size of the source image is used automatically.
By default, explicitly setting the width and height of the component causes the image to be scaled to that size. To change this behavior, set the value of the Fill mode field. Images can be stretched, tiled, or scaled uniformly to the specified size with or without cropping. The Pad option means that the image is not transformed.
Note: If the Clip check box is not selected, the component might paint outside its bounding rectangle even if the Fill mode is set to PreserveAspectCrop.
Select the Smooth check box to smoothly filter images when scaled or transformed. Smooth filtering gives better visual quality, but it may be slower on some hardware. If the image is displayed at its natural size, this property has no visual or performance effect.
Select the Mipmap check box to use mipmap filtering when scaling or transforming images. Mipmap filtering gives better visual quality when scaling down compared with smooth filtering, but it may come at a performance cost both when initializing the image and during rendering.
Select the Auto transform check box if the image should automatically apply image transformation metadata, such as EXIF orientation.
Source Size
The Source size property specifies the scaled width and height of the full-frame image. Unlike the value of the Size property, which scales the painting of the image, this property sets the maximum number of pixels stored for the loaded image so that large images do not use more memory than necessary. This ensures the image in memory is no larger than the set source size, regardless of its set size.
If the image’s actual size is larger than the source size, the image is scaled down. If only one dimension of the size is set to greater than 0, the other dimension is set in proportion to preserve the source image’s aspect ratio. The Fill mode is independent of this.
If both the source size width and height are set, the image is scaled down to fit within the specified size maintaining the image’s aspect ratio. However, if PreserveAspectCrop or PreserveAspectFit are used, the image is scaled to match the optimal size for cropping or fitting.
If the source is an intrinsically scalable image (such as SVG), source size determines the size of the loaded image regardless of intrinsic size. Avoid changing the source size property dynamically because rendering an SVG is slow compared with rendering other image formats.
If the source is a non-scalable image (such as JPEG), the loaded image will be no greater than the source size specifies. For some formats, the whole image will never actually be loaded into memory.
Note: Changing this property dynamically causes the image source to be reloaded, potentially even from the network, if it is not in the disk cache. Select the Cache check box to cache the image.
Image Alignment
You can align images horizontally and vertically in the Alignment H and Alignment V fields. By default, images are centered.
Select the Mirror check box to horizontally invert the image, effectively displaying a mirrored image.
Performance
By default, locally available images are loaded immediately, and the UI is blocked until loading is complete. If a large image is to be loaded, it may be preferable to load the image in a low priority thread, by selecting the Asynchronous check box. If the image is obtained from a network rather than a local resource, it is automatically loaded asynchronously.
Images are cached and shared internally, so if several images have the same Source, only one copy of the image will be loaded.
Note: Images are often the greatest user of memory in UIs. We recommended that you set the Source size of images that do not form a part of the UI. This is especially important for content that is loaded from external sources or provided by the user.
Border Image
The Border Image component extends the features of the Image component. It is used to create borders out of images by scaling or tiling parts of each image. A source image is broken into 9 regions that are scaled or tiled individually. The corner regions are not scaled at all, while the horizontal and vertical regions are scaled according to the values of the Tile mode H and Tile mode V field, or both.
The Stretch option scales the image to fit the available area. The Repeat option tiles the image until there is no more space. To ensure that the last image is not cropped, select the Round option that scales the images down when necessary.
Specify the regions of the image in the Border left, Border right, Border top, and Border bottom fields. The regions describe the distance from each edge of the source image to use as a border.
Note: You cannot change the Source size of a border image.
For examples of using border images, see the documentation of the BorderImage component.
Animated Image
The Animated Image component extends the features of the Image component, providing a way to play animations stored as images containing a series of frames, such as those stored in GIF files.
Set the speed of the animation in the Speed field. The speed is measured in percentage of the original animated image speed. The default speed is 1.0, which means the original speed.
To play the animation, select the Playing check box.
To pause the animation, select the (Paused) check box.
When the Cache check box is selected, every frame of the animation is cached. Deselect the check box if you are playing a long or large animation and you want to conserve memory.
If the image data comes from a sequential device (such as a socket), Animated Image can only loop if caching is enabled.
For more information, watch the following video:
Iso Icon
Note: The Iso Icon component is not available if you selected Qt 6 when creating the project.
The Iso Icon component specifies an icon from an ISO 7000 icon library as a Picture component. The icon to use for the type and its color can be specified.
To select an icon in the ISO Icon Browser in Qt Design Studio, select the ISO icon in the Navigator or 2D view, and then select Choose Icon in the context menu.
You can use the color picker in Properties to set the value of Icon color.
Summary of Images
The following table lists the components that you can use to add images. The Location column contains the tab name where you can find the component in Components. The MCU column indicates which components are supported on MCUs.
Русские Блоги
Эта статья ссылается наНастройте pycharm для преобразования .qrc в .py, Оригинальность непростая, спасибо за поддержку!
Некоторые файлы ресурсов (видео, изображения, значки, документы) более или менее используются при разработке интерфейса, чтобы сделать интерфейс более богатым.Как загрузить ресурсы в указанное место разрабатываемого интерфейса? В качестве примера возьмем загрузку изображений
состоит из трех этапов:
1. Напишите файл .qrc
В дизайне интерфейса дизайнера QT вы не можете напрямую добавлять ресурсы, такие как изображения или значки. Вам нужно написать файл .qrc в каталоге разработки (вы можете открыть его с помощью Блокнота)
После входа в дизайнер qt, создайте виджет, используйте браузер ресурсов для создания файла .qrc
Найдите несколько изображений и поместите их на свой компьютер (вы можете найти путь, я обычно помещаю их в каталог проекта), щелкните правой кнопкой мыши только что созданный файл префикса и нажмите «Добавить файл», чтобы добавить свои изображения. Обнаружена копия проблемной точки
Обычный результат выглядит следующим образом:
Перетащите метку в форму, найдите растровое изображение на панели редактирования атрибутов, нажмите «Выбрать файл» и выберите понравившееся изображение, чтобы только что выбранное изображение было загружено в метку.
Сохраните файл .UI, вы обнаружите, что в каталоге вашего проекта есть файлы .qrc и .ui, конвертируйте их в файлы .py соответственно
Полученный файл .qrc выглядит следующим образом
2、.qrc в .py руководство, пожалуйста, нажмите здесь
3、Щелкните здесь, чтобы преобразовать .ui в .py
4. Создайте логический файл.
После выполнения вышеуказанных шагов вы получите файлы .py, преобразованные из файлов .ui и .qrc.
Чтобы гарантировать разделение дизайна пользовательского интерфейса и логики,Вы можете создать еще один логический файл calluntitled.py, Напишите следующую программу
Скомпилируйте его, и следующий результат указывает на успех.
Если у вас есть вопросы, оставьте сообщение, и мы постараемся ответить.
Небольшой вопрос, как этим методом редактировать иконки интерфейса?
1. Сохраните знания: QIcon
Класс QIcon представляет значки и реализован в общей библиотеке QtGui. Объект QIcon можно рассматривать как комбинацию серии изображений, которые можно использовать для настройки значков разрабатываемого вами программного обеспечения.
2. Создайте файл .qrc.
То же, что и выше
3. Модификация файла логики
Мы хотим, чтобы в файле логики (То есть calluntitled.py)import QIcon
Вот конкретный код:
Тогда, еслиname==“main": Добавьте оператор для вызова изображения в функции
Как показано
Нажмите "Выполнить", появится следующий интерфейс.