Qt5 C++ GUI Programming Cookbook - Lee Zhi Eng - E-Book

Qt5 C++ GUI Programming Cookbook E-Book

Lee Zhi Eng

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Use Qt5 to design and build a graphical user interface that is functional, appealing, and user-friendly for your software application

About This Book

  • Learn to make use of Qt5 to design and customize the look-and-feel of your application
  • Improve the visual quality of your application by utilizing the graphic rendering system and animation system provided by Qt5
  • A good balance of visual presentation and its contents will make an application appealing yet functional

Who This Book Is For

This book intended for those who want to develop software using Qt5. If you want to improve the visual quality and content presentation of your software application, this book is best suited to you.

What You Will Learn

  • Customize the look and feel of your application using the widget editor provided by Qt5
  • Change the states of the GUI elements to make them appear in a different form
  • Animating the GUI elements using the built-in animation system provided by Qt5
  • Draw shapes and 2D images in your application using Qt5's powerful rendering system
  • Draw 3D graphics in your application by implementing OpenGL, an industry-standard graphical library to your project
  • Build a mobile app that supports touch events and export it to your device
  • Parse and extract data from an XML file, then present it on your software's GUI
  • Display web content on your program and interact with it by calling JavaScript functions from C++, or calling C++ functions from the web content
  • Access to MySQL and SQLite databases to retrieve data and display it on your software's GUI

In Detail

With the advancement of computer technology, the software market is exploding with tons of software choices for the user, making their expectations higher in terms of functionality and the look and feel of the application. Therefore, improving the visual quality of your application is vital in order to overcome the market competition and stand out from the crowd.

This book will teach you how to develop functional and appealing software using Qt5 through multiple projects that are interesting and fun. This book covers a variety of topics such as look-and-feel customization, GUI animation, graphics rendering, implementing Google Maps, and more. You will learn tons of useful information, and enjoy the process of working on the creative projects provided in this book.

Style and approach

This book focuses on customizing the look and feel and utilizing the graphical features provided by Qt5. It takes a step-by-step approach, providing tons of screenshots and sample code for you to follow and learn. Each topic is explained sequentially and placed in context.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 284

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Qt5 C++ GUI Programming Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why Subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Look and Feel Customization
Introduction
Use style sheets with Qt Designer
How to do it…
How it works...
There's more…
Basic style sheet customization
How to do it…
How it works...
Creating a login screen using style sheets
How to do it…
How it works...
Using resources in style sheets
How to do it
How it works...
Customizing properties and sub-controls
How to do it…
How it works...
Styling in QML
How to do it…
How it works...
Exposing QML object pointer to C++
How to do it…
How it works...
2. States and Animations
Introduction
Property animation in Qt
How to do it…
How it works...
There's more…
Using easing curves to control property animation
How to do it…
How it works...
There's more…
Creating an animation group
How to do it…
How it works...
There's more…
Creating a nested animation group
How to do it…
How it works...
State machines in Qt
How to do it…
How it works...
There's more…
States, transitions, and animations in QML
How to do it…
How it works...
There's more…
Animating widget properties using animators
How to do it…
How it works...
Sprite animation
How to do it…
How it works...
There's more…
3. QPainter and 2D Graphics
Introduction
Drawing basic shapes on screen
How to do it…
How it works...
There's more…
Exporting shapes to SVG files
How to do it…
How it works...
There's more…
Coordinate transformation
How to do it…
How it works...
There's more…
Displaying images on screen
How to do it…
How it works...
There's more…
Applying image effects to graphics
How to do it…
How it works...
There's more…
Creating a basic paint program
How to do it…
How it works...
2D canvas in QML
How to do it…
4. OpenGL Implementation
Introduction
Setting up OpenGL in Qt
How to do it…
How it works...
There's more…
Hello world!
How to do it…
How it works...
Rendering 2D shapes
How to do it…
How it works...
Render 3D shapes
How to do it…
How it works...
Texturing in OpenGL
How to do it…
How it works...
Lighting and texture filter in OpenGL
How to do it…
How it works...
There's more…
Moving an object using keyboard controls
How to do it…
How it works...
3D canvas in QML
How to do it…
How it works...
5. Building a Touch Screen Application with Qt5
Introduction
Setting up Qt for mobile applications
How to do it…
How it works…
Designing a basic user interface with QML
How to do it…
How it works…
Touch events
How to do it…
How it works…
There's more…
Animation in QML
How to do it…
How it works…
Displaying information using Model View
How to do it…
How it works…
Integrating QML and C++
How to do it…
How it works…
6. XML Parsing Made Easy
Introduction
Processing XML data using stream reader
How to do it…
How it works…
There's more…
Writing XML data using Stream Writer
How to do it…
How it works…
Processing XML data using the QDomDocument class
How to do it…
How it works…
Writing XML data using the QDomDocument class
How to do it…
How it works…
Using Google's Geocoding API
How to do it…
How it works…
There's more…
7. Conversion Library
Introduction
Data conversion
How to do it…
How it works...
There's more…
Image conversion
How to do it…
How it works...
There's more…
Video conversion
How to do it…
How it works...
There's more…
Currency conversion
How to do it…
How it works...
There's more…
8. Accessing Databases
Introduction
How to do it…
How it works…
Connecting to a database
How to do it…
How it works…
Writing basic SQL queries
How to do it…
How it works…
Creating a login screen with Qt
How to do it…
How it works…
Displaying information from a database on a model view
How to do it…
How it works…
Advanced SQL queries
How to do it…
How it works…
There's more…
9. Developing a Web Application Using Qt Web Engine
Introduction
Introduction to Qt WebEngine
How to do it…
How it works…
There's more…
WebView and web settings
How to do it…
How it works…
Embedding Google Maps in your project
How to do it…
How it works…
Calling C++ functions from JavaScript
How to do it…
How it works…
Calling JavaScript functions from C++
How to do it…
How it works…
Index

Qt5 C++ GUI Programming Cookbook

Qt5 C++ GUI Programming Cookbook

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2016

Production reference: 1220716

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78328-027-8

www.packtpub.com

Credits

Author

Lee Zhi Eng

Reviewer

Symeon Huang

Commissioning Editor

Kartikey Pandey

Acquisition Editor

Indrajit Das

Content Development Editor

Priyanka Mehta

Technical Editors

Dhiraj Chandanshive

Ravikiran Pise

Copy Editor

Safis Editing

Project Coordinator

Izzat Contractor

Proofreader

Safis Editing

Indexer

Rekha Nair

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Lee Zhi Eng is a 3D artist-turned-programmer who worked in the video game industry as a game artist, game programmer, and a game programming lecturer. Later, he decided to take a break from games and ventured into software engineering by co-founding his current company, Reonyx Tech. Since then, he has been involved in multiple projects that are different from what he used to do, including geolocation and near-real-time navigation systems, Big Data analytics, and augmented reality. You can find out more about him at http://www.zhieng.com, or you can find out about his company at http://www.reonyx.com.

About the Reviewer

Symeon Huang is an experienced C++ GUI software developer and the author of Qt 5 Blueprints, Packt Publishing. He has finished his master's degree in high performance computing and has been working as a software engineer in industry.

I'd like to thank Packt Publishing for giving me the opportunity to review this book. As a reviewer, I've also learnt from this book and I'm sure this book will be of great use to all readers.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

The continuous growth of the computer software market leads to a very competitive and challenging era. Not only does your software need to be functional and easy to use, it must also look appealing and professional to the users. In order to gain an upper hand and a competitive advantage over other software products in the market, the look and feel of your product is of utmost importance and should be taken care of early in the production stage. In this book, we will teach you how to create a functional, appealing, and user friendly software using the Qt5 development platform.

What this book covers

Chapter 1, Look and Feel Customization, shows how to design your program's user interface using both the Qt Designer as well as the Qt Quick Designer.

Chapter 2, States and Animations, explains how to animate your user interface widgets by empowering the state machine framework and the animation framework.

Chapter 3, QPainter and 2D Graphics, covers how to draw vector shapes and bitmap images on screen using Qt's built-in classes.

Chapter 4, OpenGL Implementation, demonstrates how to render 3D graphics in your program by integrating OpenGL in your Qt project.

Chapter 5, Building a Touch Screen Application with Qt5, explains how to create a program that works on a touch screen device.

Chapter 6, XML Parsing Made Easy, shows how to process data in the XML format and use it together with the Google Geocoding API to create a simple address finder.

Chapter 7, Conversion Library, covers how to convert between different variable types, image formats, and video formats using Qt's built-in classes as well as third-party programs.

Chapter 8, Accessing Databases, explains how to connect your program to an SQL database using Qt.

Chapter 9, Developing a Web Application Using Qt Web Engine, covers how to use the web rendering engine provided by Qt and develop programs that empower the web technology.

What you need for this book

The following are the prerequisites for this book:

Qt5 (for all chapters)FFmpeg (for Chapter 7, Conversion Library)XAMPP (for Chapter 8, Accessing Databases)

Who this book is for

This book intended for those who want to develop software using Qt5. If you want to improve the visual quality and content presentation of your software application, this book will suit you best.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "In the mylabel.cpp source file, define a function called SetMyObject() to save the object pointer."

A block of code is set as follows:

QSpinBox::down-button { image: url(:/images/spindown.png); subcontrol-origin: padding; subcontrol-position: right bottom; }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

QSpinBox::down-button { image: url(:/images/spindown.png); subcontrol-origin: padding; subcontrol-position: right bottom; }

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Go to the Imports tab in the Library window and add a Qt Quick module called QtQuick.Controls to your project."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Qt5-C-GUI-Programming-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Qt5C++GUIProgrammingCookbook_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Look and Feel Customization

In this chapter we will cover the following recipes:

Using style sheets with Qt DesignerBasic style sheet customizationCreating a login screen using style sheetsUsing resources in style sheetsCustomizing properties and sub-controlsStyling in QMLExposing QML object pointer to C++

Introduction

Qt allows us to easily design our program's user interface through a method that most people are familiar with. Qt not only provides us with a powerful user interface toolkit called Qt Designer, which enables us to design our user interface without writing a single line of code, but it also allows advanced users to customize their user interface components through a simple scripting language called Qt Style Sheets.

Use style sheets with Qt Designer

In this example, we will learn how to change the look and feel of our program and make it look more professional by using style sheets and resources. Qt allows you to decorate your Graphical User Interfaces (GUIs) using a style sheet language called Qt Style Sheets, which is very similar to Cascading Style Sheets (CSS) used by web designers to decorate their websites.

How to do it…

The first thing we need to do is open up Qt Creator and create a new project. If this is the first time you have used Qt Creator, you can either click the big button that says New Project with a + sign, or simply go to File | New File or New Project.Then, select Application under the Project window and select Qt Widgets Application.After that, click the Choose button at the bottom. A window will then pop out and ask you to insert the project name and its location.Once you're done with that, click Next several times and click the Finish button to create the project. We will just stick to all the default settings for now. Once the project has been created, the first thing you will see is the panel with tons of big icons on the left side of the window that is called the Mode Selector panel; we will discuss this more later in the How it works... section.Then, you will also see all your source files listed on the Side Bar panel which is located right next to the Mode Selector panel. This is where you can select which file you want to edit, which, in this case, is mainwindow.ui because we are about to start designing the program's UI!Double-click mainwindow.ui and you will see an entirely different interface appearing out of nowhere. Qt Creator actually helped you to switch from the script editor to the UI editor (Qt Designer) because it detected the .ui extension on the file you're trying to open.You will also notice that the highlighted button on the Mode Selector panel has changed from the Edit button to the Design button. You can switch back to the script editor or change to any other tools by clicking one of the buttons located in the upper half of the Mode Selector panel.Let's go back to the Qt Designer and look at the mainwindow.ui file. This is basically the main window of our program (as the filename implies) and it's empty by default, without any widget on it. You can try to compile and run the program by pressing the Run button (green arrow button) at the bottom of the Mode Selector panel, and you will see an empty window popping up once the compilation is complete:Now, let's add a push button to our program's UI by clicking on the Push Button item in the widget box (under the Buttons category) and dragging it to your main window in the form editor. Then, keep the push button selected, and now you will see all the properties of this button inside the property editor on the right side of your window. Scroll down to somewhere around the middle and look for a property called styleSheet. This is where you apply styles to your widget, which may or may not inherit to its children or grandchildren recursively depending on how you set your style sheet. Alternatively, you can also right-click on any widget in your UI at the form editor and select Change Style Sheet from the pop-up menu.You can click on the input field of the styleSheet property to directly write the style sheet code, or click on the … button besides the input field to open up the Edit Style Sheet window which has a bigger space for writing longer style sheet code. At the top of the window you can find several buttons, such as Add Resource, Add Gradient, Add Color, and Add Font, that can help you to kick-start your coding if you can't remember the properties' names.

Let's try to do some simple styling with the Edit Style Sheet window.

Click Add Color and choose color.Pick a random color from the color picker window, let's say, a pure red color. Then click OK.Now, you will see a line of code has been added to the text field on the Edit Style Sheet window, which in my case is as follows:

color: rgb(255, 0, 0);

Click the OK button and now you will see the text on your push button has changed to a red color.

How it works...

Let's take a bit of time to get ourselves familiar with Qt Designer's interface before we start learning how to design our own UI:

Menu bar: The menu bar houses application-specific menus that provide easy access to essential functions such as create new projects, save files, undo, redo, copy, paste, and so on. It also allows you to access development tools that come with Qt Creator, such as the compiler, debugger, profiler, and so on.Widget box: This is where you can find all the different types of widget provided by Qt Designer. You can add a widget to your program's UI by clicking one of the widgets from the widget box and dragging it to the form editor.Mode selector: The mode selector is a side panel that places shortcut buttons for easy access to different tools. You can quickly switch between the script editor and form editor by clicking the Edit or Design buttons on the mode selector panel which is very useful for multitasking. You can also easily navigate to the debugger and profiler tools in the same speed and manner.Build shortcuts: The build shortcuts are located at the bottom of the mode selector panel. You can build, run, and debug your project easily by pressing the shortcut buttons here.Form editor: Form editor is where you edit your program's UI. You can add different widgets to your program by selecting a widget from the widget box and dragging it to the form editor.Form toolbar: From here, you can quickly select a different form to edit, click the drop-down box located above the widget box and select the file you want to open with Qt Designer. Beside the drop-down box are buttons for switching between different modes for the form editor and also buttons for changing the layout of your UI.Object inspector: The object inspector lists all the widgets within your current .ui file. All the widgets are arranged according to its parent-child relationship in the hierarchy. You can select a widget from the object inspector to display its properties in the property editor.Property editor: Property editor will display all the properties of the widget you selected either from the object inspector window or the form editor window.Action Editor and Signals & Slots Editor: This window contains two editors, Action Editor and the Signals & Slots Editor, which can be accessed from the tabs below the window. The action editor is where you create actions that can be added to a menu bar or toolbar in your program's UI.Output panes: Output panes consist of several different windows that display information and output messages related to script compilation and debugging. You can switch between different output panes by pressing the buttons that carry a number before them, such as 1-Issues, 2-Search Results, 3-Application Output, and so on.

There's more…

In the previous section, we discussed how to apply style sheets to Qt widgets through C++ coding. Although that method works really well, most of the time the person who is in charge of designing the program's UI is not the programmer, but a UI designer who specializes in designing user-friendly UI. In this case, it's better to let the UI designer design the program's layout and style sheet with a different tool and not mess around with the code.

Qt provides an all-in-one editor called Qt Creator. Qt Creator consists of several different tools, such as script editor, compiler, debugger, profiler, and UI editor. The UI editor, which is also called Qt Designer, is the perfect tool for designers to design their program's UI without writing any code. This is because Qt Designer adopted the What-You-See-Is-What-You-Get approach by providing accurate visual representation of the final result, which means whatever you design with Qt Designer will turn out exactly the same when the program is compiled and run.

The similarities between Qt Style Sheets and CSS are as follows:

CSS: h1 { color: red; background-color: white;}Qt Style Sheets: QLineEdit { color: red; background-color: white;}As you can see, both of them contain a selector and a declaration block. Each declaration contains a property and a value, separated by a colon.In Qt, a style sheet can be applied to a single widget by calling QObject::setStyleSheet() function in C++ code, for example:
myPushButton->setStyleSheet("color : blue");
The preceding code will turn the text of a button with the variable name myPushButton to a blue color. You can also achieve the same result by writing the declaration in the style sheet property field in Qt Designer. We will discuss more about Qt Designer in the next section.Qt Style Sheets also supports all the different types of selectors defined in CSS2 standard, including Universal selector, Type selector, Class selector, ID selector, and so on, which allows us to apply styling to a very specific individual or group of widgets. For instance, if we want to change the background color of a specific line edit widget with the object name usernameEdit, we can do this by using an ID selector to refer to it:
QLineEdit#usernameEdit { background-color: blue }

Note

To learn about all the selectors available in CSS2 (which are also supported by Qt Style Sheets), please refer to this document: http://www.w3.org/TR/REC-CSS2/selector.html.

Basic style sheet customization

In the previous example, you learned how to apply a style sheet to a widget with Qt Designer. Let's go crazy and push things further by creating a few other types of widgets and change their style properties to something bizarre for the sake of learning. This time, however, we will not apply the style to every single widget one by one, but we will learn to apply the style sheet to the main window and let it inherit down the hierarchy to all the other widgets so that the style sheet is easier to manage and maintain in long run.

How to do it…

First of all, let's remove the style sheet from the push button by selecting it and clicking the small arrow button besides the styleSheet property. This button will revert the property to the default value, which in this case is the empty style sheet.Then, add a few more widgets to the UI by dragging them one by one from the widget box to the form editor. I've added a line edit, combo box, horizontal slider, radio button, and a check box.For the sake of simplicity, delete the menu bar, main toolbar, and the status bar from your UI by selecting them from the object inspector, right click, and choose Remove. Now your UI should look similar to this:Select the main window either from the form editor or the object inspector, then right click and choose Change Stylesheet to open up the Edit Style Sheet.

Insert the following style sheet:

border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow;
Now what you will see is a completely bizarre-looking UI with everything covered in yellow with a thick border. This is because the preceding style sheet does not have a selector, which means the style will apply to the children widgets of the main window all the way down the hierarchy. To change that, let's try something different:
QPushButton { border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow; }
This time, only the push button will get the style described in the preceding code, and all other widgets will return to the default styling. You can try to add a few more push buttons to your UI and they will all look the same:This happens because we specifically tell the selector to apply the style to all the widgets with the class called QPushButton. We can also apply the style to just one of the push buttons by mentioning its name in the style sheet, like so:
QPushButton#pushButton_3 { border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow; }
Once you understand this method, we can add the following code to the style sheet :
QPushButton{ color: red; border: 0px; padding: 0 8px; background: white;}QPushButton#pushButton_2{ border: 1px solid red; border-radius: 10px;} QPushButton#pushButton_3 { border: 2px solid gray; border-radius: 10px; padding: 0 8px; background: yellow; }
What it does is basically change the style of all the push buttons as well as some properties of a specific button named pushButton_2. We keep the style sheet of pushButton_3 as it is. Now the buttons will look like this:The first set of style sheet will change all widgets of QPushButton type to a white rectangular button with no border and red text. Then the second set of style sheet changes only the border of a specific QPushButton widget called pushButton_2. Notice that the background color and text color of pushButton_2 remain white and red respectively because we didn't override them in the second set of style sheet, hence it will return to the style described in the first set of style sheet since it's applicable to all QPushButton widgets. Do notice that the text of the third button has also changed to red because we didn't describe the color property in the third set of style sheet.After that, create another set of style using the universal selector, like so:
* { background: qradialgradient(cx: 0.3, cy: -0.4, fx: 0.3, fy: -0.4, radius: 1.35, stop: 0 #fff, stop: 1 #888); color: rgb(255, 255, 255); border: 1px solid #ffffff; }
The universal selector will affect all the widgets regardless of their type. Therefore, the preceding style sheet will apply a nice gradient color to all the widgets' background as well as setting their text as white and giving them a one-pixel solid outline which is also in white. Instead of writing the name of the color (that is, white), we can also use the rgb function (rgb(255, 255, 255)) or hex code (#ffffff) to describe the color value.Just as before, the preceding style sheet will not affect the push buttons because we have already given them their own styles which will override the general style described in the universal selector. Just remember that in Qt, the style that is more specific will ultimately be used when there is more than one style having influence on a widget. This is how the UI will look now:

How it works...

If you are ever involved in web development using HTML and CSS, Qt's style sheet works exactly the same way as CSS. Style sheets provide the definitions for describing the presentation of the widgets – what the colors are for each element in the widget group, how thick the border should be, and so on and so forth.

If you specify the name of the widget to the style sheet, it will change the style of a particular push button widget with the name you provide. None of the other widgets will be affected and will remain as the default style.

To change the name of a widget, select the widget either from the form editor or the object inspector and change the property called objectName in the property window. If you have used the ID selector previously to change the style of the widget, changing its object name will break the style sheet and lose the style. To fix this problem, simply change the object name in the style sheet as well.