Как изменить цвет кнопки qt c
Перейти к содержимому

Как изменить цвет кнопки qt c

  • автор:

Изменение цвета кнопки в QT Creator

Но каждый раз, когда я qmake, Ui_Window.h получает переделку, и я теряю свои цвета.

Кто-нибудь знает, как постоянно сохранять цвета кнопки? Я работаю с QT Creator. Если бы кто-то мог направить меня = D

3 ответа

Самый простой способ — использовать таблицу стилей на кнопке:

Aero, учтите, что вы НЕ ДОЛЖНЫ изменять файл Ui_Window.h, поскольку он создан Qt Designer. Таким образом, каждый раз, когда вы перекомпилируете файл .ui, этот файл заголовка будет перезаписан. Как я вижу, вы используете Qt Designer для добавления кнопок в макет. В этом случае вы можете щелкнуть правой кнопкой мыши по виджету (или в главном диалоговом окне) в Qt Designer и нажать «Изменить макет. «. Там вы можете сделать что-то вроде:

для всех кнопок или для конкретной кнопки:

Скажите, если это сработает для вас. Cheers,

Если вы используете свою форму только в одном классе, вы можете добавить там свое выражение после вызова ui->setupUi() в нем. Или даже добавьте таблицу стилей непосредственно в форму, найдите свойство «StyleSheet» в представлении свойств конструктора Qt.

Changing the color of a Push Button in QT Creator

But everytime I qmake, the Ui_Window.h gets remade and I lose my colors.

Does anyone know how to permanently keep the colors of the button? I am working with QT Creator. If someone could direct me =D

3 Answers 3

Easiest way would be to use a style sheet on the button:

Aero, take into account that you MUST not modify Ui_Window.h file since it is generated by Qt Designer. So, every time you recompile the .ui file, this header file will be overwriten. As I see, you are using Qt Designer to add buttons to the layout. In this case, you can right click on a widget (or in the main dialog) in Qt Designer and click then in ‘Change layout. ‘. On there, you can do something like:

Qt Style Sheets Examples

We will now see a few examples to get started with using Qt Style Sheets.

Style Sheet Usage

Customizing the Foreground and Background Colors

Let’s start by setting yellow as the background color of all QLineEdits in an application. This could be achieved like this:

If we want the property to apply only to the QLineEdits that are children (or grandchildren or grand-grandchildren) of a specific dialog, we would rather do this:

If we want the property to apply only to one specific QLineEdit, we can give it a name using QObject::setObjectName() and use an ID Selector to refer to it:

Alternatively, we can set the background-color property directly on the QLineEdit, omitting the selector:

To ensure a good contrast, we should also specify a suitable color for the text:

It might be a good idea to change the colors used for selected text as well:

Customizing Using Dynamic Properties

There are many situations where we need to present a form that has mandatory fields. To indicate to the user that the field is mandatory, one effective (albeit esthetically dubious) solution is to use yellow as the background color for those fields. It turns out this is very easy to implement using Qt Style Sheets. First, we would use the following application-wide style sheet:

This means that every widget whose mandatoryField Qt property is set to true would have a yellow background.

Then, for each mandatory field widget, we would simply create a mandatoryField property on the fly and set it to true. For example:

Customizing a QPushButton Using the Box Model

This time, we will show how to create a red QPushButton. This QPushButton would presumably be connected to a very destructive piece of code.

First, we are tempted to use this style sheet:

However, the result is a boring, flat button with no borders:

What happened is this:

  • We have made a request that cannot be satisfied using the native styles alone (e.g., the Windows Vista theme engine doesn’t let us specify the background color of a button).
  • Therefore, the button is rendered using style sheets.
  • We haven’t specified any values for border-width and border-style, so by default we obtain a 0-pixel wide border of style none .

Let’s improve the situation by specifying a border:

Things look already a lot better. But the button looks a bit cramped. Let’s specify some spacing between the border and the text using the padding. Additionally, we will enforce a minimum width, round the corners, and specify a larger font to make the button look nicer:

The only issue remaining is that the button doesn’t react when we press it. We can fix this by specifying a slightly different background color and use a different border style.

Customizing the QPushButton’s Menu Indicator Sub-Control

Subcontrols give access to the sub-elements of a widget. For example, a QPushButton associated with a menu (using QPushButton::setMenu()) has a menu indicator. Let’s customize the menu indicator for the red push button:

By default, the menu indicator is located at the bottom-right corner of the padding rectangle. We can change this by specifying subcontrol-position and subcontrol-origin to anchor the indicator differently. We can also use top and left to move the indicator by a few pixels. For example:

This positions the myindicator.png to the center right of the QPushButton’s padding rectangle (see subcontrol-origin for more information).

Complex Selector Example

Since red seems to be our favorite color, let’s make the text in QLineEdit red by setting the following application-wide stylesheet:

However, we would like to give a visual indication that a QLineEdit is read-only by making it appear gray:

At some point, our design team comes with the requirement that all QLineEdits in the registration form (with the object name registrationDialog ) to be brown:

A few UI design meetings later, we decide that all our QDialogs should have brown colored QLineEdits:

Quiz: What happens if we have a read-only QLineEdit in a QDialog? [Hint: The Conflict Resolution section above explains what happens in cases like this.]

Customizing Specific Widgets

This section provides examples to customize specific widgets using Style Sheets.

Customizing QAbstractScrollArea

The background of any QAbstractScrollArea (Item views, QTextEdit and QTextBrowser) can be set using the background properties. For example, to set a background-image that scrolls with the scroll bar:

If the background-image is to be fixed with the viewport:

Customizing QCheckBox

Styling of a QCheckBox is almost identical to styling a QRadioButton. The main difference is that a tristate QCheckBox has an indeterminate state.

Customizing QComboBox

We will look at an example where the drop down button of a QComboBox appears «merged» with the combo box frame.

The pop-up of the QComboBox is a QAbstractItemView and is styled using the descendant selector:

Customizing QDockWidget

The title bar and the buttons of a QDockWidget can be customized as follows:

If one desires to move the dock widget buttons to the left, the following style sheet can be used:

Note: To customize the separator (resize handle) of a QDockWidget, use QMainWindow::separator.

Customizing QFrame

A QFrame is styled using the The Box Model.

Customizing QGroupBox

Let us look at an example that moves the QGroupBox’s title to the center.

For a checkable QGroupBox, use the <#indicator-sub> <::indicator>subcontrol and style it exactly like a QCheckBox (i.e)

Customizing QHeaderView

QHeaderView is customized as follows:

Customizing QLineEdit

The frame of a QLineEdit is styled using the The Box Model. To create a line edit with rounded corners, we can set:

The password character of line edits that have QLineEdit::Password echo mode can be set using:

The background of a read only QLineEdit can be modified as below:

Customizing QListView

The background color of alternating rows can be customized using the following style sheet:

To provide a special background when you hover over items, we can use the ::item subcontrol. For example,

Customizing QMainWindow

The separator of a QMainWindow can be styled as follows:

Customizing QMenu

Individual items of a QMenu are styled using the ‘item’ subcontrol as follows:

For a more advanced customization, use a style sheet as follows:

Customizing QMenuBar

QMenuBar is styled as follows:

Customizing QProgressBar

The QProgressBar’s border, chunk, and text-align can be customized using style sheets. However, if one property or sub-control is customized, all the other properties or sub-controls must be customized as well.

For example, we change the border to grey and the chunk to cerulean.

This leaves the text-align, which we customize by positioning the text in the center of the progress bar.

A margin can be included to obtain more visible chunks.

In the screenshot above, we use a margin of 0.5 pixels.

Customizing QPushButton

A QPushButton is styled as follows:

For a QPushButton with a menu, use the ::menu-indicator subcontrol.

Checkable QPushButton have the :checked pseudo state set.

Customizing QRadioButton

The indicator of a QRadioButton can be changed using:

Customizing QScrollBar

The QScrollBar can be styled using its subcontrols like handle, add-line, sub-line, and so on. Note that if one property or sub-control is customized, all the other properties or sub-controls must be customized as well.

The scroll bar above has been styled in aquamarine with a solid grey border.

The left-arrow and right-arrow have a solid grey border with a white background. As an alternative, you could also embed the image of an arrow.

If you want the scroll buttons of the scroll bar to be placed together (instead of the edges) like on macOS, you can use the following stylesheet:

The scroll bar using the above stylesheet looks like this:

To customize a vertical scroll bar use a style sheet similar to the following:

Customizing QSizeGrip

QSizeGrip is usually styled by just setting an image.

Customizing QSlider

You can style horizontal slider as below:

If you want to change the color of the slider parts before and after the handle, you can use the add-page and sub-page subcontrols. For example, for a vertical slider:

Customizing QSpinBox

QSpinBox can be completely customized as below (the style sheet has commentary inline):

Customizing QSplitter

A QSplitter derives from a QFrame and hence can be styled like a QFrame. The grip or the handle is customized using the ::handle subcontrol.

Customizing QStatusBar

We can provide a background for the status bar and a border for items inside the status bar as follows:

Note that widgets that have been added to the QStatusBar can be styled using the descendant declaration (i.e)

Customizing QTabWidget and QTabBar

For the screenshot above, we need a stylesheet as follows:

Often we require the tabs to overlap to look like below:

For a tab widget that looks like above, we make use of negative margins. Negative values draw the element closer to its neighbors than it would be by default. The resulting stylesheet looks like this:

To move the tab bar to the center (as below), we require the following stylesheet:

The tear indicator and the scroll buttons can be further customized as follows:

Since Qt 4.6 the close button can be customized as follow:

Customizing QTableView

Suppose we’d like our selected item in QTableView to have bubblegum pink fade to white as its background.

This is possible with the selection-background-color property and the syntax required is:

The corner widget can be customized using the following style sheet

The QTableView’s checkbox indicator can also be customized. In the following snippet the indicator background-color in unchecked state is customized:

Customizing QToolBar

The background and the handle of a QToolBar is customized as below:

Customizing QToolBox

The tabs of the QToolBox are customized using the ‘tab’ subcontrol.

Customizing QToolButton

There are three types of QToolButtons.

  • The QToolButton has no menu. In this case, the QToolButton is styled exactly like QPushButton. See Customizing QPushButton for an example.
  • The QToolButton has a menu and has the QToolButton::popupMode set to QToolButton::DelayedPopup or QToolButton::InstantPopup. In this case, the QToolButton is styled exactly like a QPushButton with a menu. See Customizing QPushButton for an example of the usage of the menu-indicator pseudo state.
  • The QToolButton has its QToolButton::popupMode set to QToolButton::MenuButtonPopup. In this case, we style it as follows:

Customizing QToolTip

QToolTip is customized exactly like a QLabel. In addition, for platforms that support it, the opacity property may be set to adjust the opacity.

Customizing QTreeView

The background color of alternating rows can be customized using the following style sheet:

To provide a special background when you hover over items, we can use the ::item subcontrol. For example,

The branches of a QTreeView are styled using the ::branch subcontrol. The following stylesheet color codes the various states when drawing a branch.

Colorful, though it is, a more useful example can be made using the following images:

vline.png branch-more.png branch-end.png branch-closed.png branch-open.png

The resulting tree view looks like this:

Common Mistakes

This section lists some common mistakes when using stylesheets.

QPushButton and images

When styling a QPushButton, it is often desirable to use an image as the button graphic. It is common to try the background-image property, but this has a number of drawbacks: For instance, the background will often appear hidden behind the button decoration, because it is not considered a background. In addition, if the button is resized, the entire background will be stretched or tiled, which does not always look good.

It is better to use the border-image property, as it will always display the image, regardless of the background (you can combine it with a background if it has alpha values in it), and it has special settings to deal with button resizing.

Consider the following snippet:

This will produce a button looking like this:

The numbers after the url gives the top, right, bottom and left number of pixels, respectively. These numbers correspond to the border and should not stretch when the size changes. Whenever you resize the button, the middle part of the image will stretch in both directions, while the pixels specified in the stylesheet will not. This makes the borders of the button look more natural, like this:

With borders
Without borders

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

Поменять цвет QPushButton, QLabel

Добрый день. Может вопрос покажется кому то довольно глупым , но разобраться сам не смог ( сразу скажу гуглил — ничего не нашел ) В общем проблема такая, например , создаю Виджет, допустим, QPushButton в Qt designer. Не получается изменить его цвет, вставить картинку и т.д. — методы setColor и setIcon не работают. Менял используя setStyleSheet, но это не всегда удобно. Либо создавая в конструкторе Виджета, например, QLabel. Делал с ним что хочу, вот как то так:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *