Real Python: Python and PyQt: Creating Menus, Toolbars, and Status Bars

Real Python: Python and PyQt: Creating Menus, Toolbars, and Status Bars

https://ift.tt/3kI1ZXi

When it comes to developing graphical user interface (GUI) applications with Python and PyQt, some of the most useful and versatile graphical elements that you’ll ever use are menus, toolbars, and status bars.

Menus and toolbars can make your applications look polished and professional, presenting users with an accessible set of options, while status bars allow you to display relevant information about the application’s status.

In this tutorial, you’ll learn:

  • What menus, toolbars, and status bars are
  • How to create menus, toolbars, and status bars programmatically
  • How to populate Python menu and toolbar using PyQt actions
  • How to use status bars to display status information

In addition, you’ll learn some programming best practices that you can apply when creating menus, toolbars, and status bars with Python and PyQt. If you’re new to GUI programming with PyQt, then you can check out Python and PyQt: Building a GUI Desktop Calculator.

You can download the code and resources for the sample application that you’ll build in this tutorial by clicking on the box below:

Download the sample code: Click here to get the code you’ll use to learn how to add menus, toolbars, and status bars to your GUI applications using Python and PyQt.

Building Python Menu Bars, Menus, and Toolbars in PyQt

A menu bar is a region of a GUI application’s main window that holds menus. Menus are pull-down lists of options that provide convenient access to your application’s options. For example, if you were creating a text editor, then you might have some of the following menus in your menu bar:

  • A File menu that provides some of the following menu options:
    • New for creating a new document
    • Open for opening an existing document
    • Open Recent for opening recent documents
    • Save for saving a document
    • Exit for exiting the application
  • An Edit menu that provides some of the following menu options:
    • Copy for copying some text
    • Paste for pasting some text
    • Cut for cutting some text
  • A Help menu that provides some of the following menu options:
    • Help Content for launching to user’s manual and help content
    • About for launching an About dialog

You can also add some of these options to a toolbar. A toolbar is a panel of buttons with meaningful icons that provide fast access to the most commonly used options in an application. In your text editor example, you could add options like New, Open, Save, Copy, and Paste to a toolbar.

Note: In this tutorial, you’ll develop a sample application that implements all the above menus and options. You can use this sample application as a starting point to create a text editor project.

In this section, you’ll learn the basics of how to add menu bars, menus, and toolbars to your GUI applications with Python and PyQt.

Before going any further, you’ll create a sample PyQt application that you’ll use throughout this tutorial. In each section, you’ll add new features and functionalities to this sample application. The application will be a main window–style application. This means that it’ll have a menu bar, a toolbar, a status bar, and a central widget.

Open your favorite code editor or IDE and create a Python file called sample_app.py. Then add the following code to it:

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow

class Window(QMainWindow):
    """Main Window."""
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)
        self.setWindowTitle("Python Menus & Toolbars")
        self.resize(400, 200)
        self.centralWidget = QLabel("Hello, World")
        self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.setCentralWidget(self.centralWidget)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

Now sample_app.py contains all the code that you need for creating your sample PyQt application. In this case, Window inherits from QMainWindow. So, you’re building a main window–style application.

Note: Unfortunately, PyQt5’s official documentation has some incomplete sections. To work around this, you can check out either the PyQt4 documentation or the original Qt documentation.

In the class initializer .__init__(), you first call the parent class’s initializer using super(). Then you set the title of the window using .setWindowTitle() and resize the window using .resize().

Note: If you aren’t familiar with PyQt applications and how to create them, then you can check out Python and PyQt: Building a GUI Desktop Calculator.

The window’s central widget is a QLabel object that you’ll use to show messages in response to certain user actions. These messages will display at the center of the window. To do this, you call .setAlignment() on the QLabel object with a couple of alignment flags.

If you run the application from your command line, then you’ll see the following window on your screen:

PyQt Sample Application

That’s it! You’ve created a main window–style application with Python and PyQt. You’ll use this sample application for all the upcoming examples in this tutorial.

Creating Menu Bars

Read the full article at https://realpython.com/python-menus-toolbars/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Python

via Planet Python https://ift.tt/1dar6IN

November 16, 2020 at 11:50AM

Python Morsels: How to Make a Function

Python Morsels: How to Make a Function

https://ift.tt/32LVk88



Related article:

Transcript:

How can you make your own function in Python?

Defining a function

Let’s make a function called greet that prints out "Hello world".

>>> def greet():
...     print("Hello world")
...

You can put as many statements as you like in a function, but we’ve chosen to just put one statement in this greet function.

When we call greet (by specifying the name of the function and open and close parentheses) Python will execute the statements inside that function:

>>> greet()
Hello world

If we pass an argument to the greet function, we’ll get an error:

>>> greet("Trey")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: greet() takes 0 positional arguments but 1 was given

We got an error because we passed an argument to greet but the greet function takes zero positional arguments.

Accepting arguments

To make a function that accepts arguments, you put the arguments in the parentheses when defining it.

Here we’ll modify our greet function to print out "Hello" and a name variable (instead of "world"):

>>> def greet(name):
...     print("Hello", name)
...

If we call this new greet function, we can pass a value to the name argument to print out that name:

>>> greet("Trey")
Hello Trey

So we use def to define a function, we type the name of the function we’re defining, and then we put parentheses.
Inside the parenthesis we put any arguments that our function accepts (if there’s more than one argument, they’re separated by commas).
That first line is always followed by a colon, which indicates the start of a block of code (meaning all the statements in the function are indented).

Positional vs keyword arguments

If we take the greet function and call it with Trey, this is a positional argument.
We can also pass in a keyword argument or a named argument.

We could pass the name in using a keyword argument like this:

>>> greet(name="Trey")
Hello Trey

Default argument values

If we don’t give any arguments to this function we’ll see an error because the greet function accepts a name argument, and it’s required:

>>> greet()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: greet() missing 1 required positional argument: 'name'

Function arguments are required by default in Python.
If you want to make optional arguments, you need to provide a default value.
We can specify a default value with an equals sign:

>>> def greet(name="world"):
...     print("Hello", name)
...

Note: that equals sign doesn’t have anything to do with keyword arguments.
When you call a function an equal sign specifies a keyword argument.
When you define a function, an equal sign defines a default value for an argument.

If we call this function with an argument it does the same thing as before:

>>> greet("Trey")
Hello Trey

But if we don’t supply an value for that argument, name will default to world.

>>> greet()
Hello world

Return values

Let’s take a function, product that accepts two arguments, numbers and start (which defaults to 1):

>>> def product(numbers, start=1):
...     total = start
...     for n in numbers:
...         total *= n
...     print(total)
...

This product function doesn’t really work the way it probably should.

When we call product with some numbers, 6 is printed out:

>>> total = product([2, 1, 3])
6

We would expect the variable total to be 6.
But it’s not 6: it is None!

>>> total
>>> print(total)
None

None is the default return value for all functions.

Arguments are the inputs to a function.
The return value is the output of a function.

Normally you’ll want your functions to have a return statement.

Let’s change the product function to return instead of calling print:

>>> def product(numbers, start=1):
...     total = start
...     for n in numbers:
...         total *= n
...     return total
...

Now that we’ve changed print to return, if we execute the same sort of code as before we’ll see nothing is printed out.

>>> total = product([2, 1, 3, 4])

But total is 24 now:

>>> total
24

When you call a function, it’s return value will be passed back to you, the caller of that function, and we can capture that into a variable or pass it off somewhere else.

Summary

To define a function in Python, you use the def keyword.
You put the name of the function, open and close parentheses, with any arguments inside those parentheses.
If any of the arguments are optional, you’ll need to give them default values.

Then you put a colon, to start defining the body of the function (a colon means you’ve got a block of code that’s going to be indented).
The statements you write will be executed when that function is called.

Importantly functions have inputs, which are their arguments and also an output, which is the return value of that function, which isn’t required, but most functions have a return value.

That’s how you make a function in Python!

Python

via Planet Python https://ift.tt/1dar6IN

November 16, 2020 at 02:54PM

Encrypting and signing data using private/public keys in PHP

Encrypting and signing data using private/public keys in PHP

https://ift.tt/35rI4Hr


For a project, I needed to make sure that a particular piece of data actually came from a specific source. There are already many packages that allow you to do this, but most are not fun or easy to use. That’s why we created a new package called spatie/crypto to do this.

Using spatie/crypto #

Using this package, it’s easy to generate a private and public key.

[$privateKey, $publicKey] = (new Spatie\Crypto\RsaKeyPair())->generate();

When passing paths, the generated keys will be passed to those paths.

(new KeyPair())->generate($pathToPrivateKey, $pathToPublicKey);

Using a private key, you can sign a message.

$privateKey = Spatie\Crypto\Rsa\PrivateKey::fromFile($pathToPrivateKey);
$signature = $privateKey->sign('my message'); 

The public key can use the signature to determine that the message was not tampered with.

$publicKey = Spatie\Crypto\Rsa\PublicKey::fromFile($pathToPublicKey);

$publicKey->verify('my message', $signature) 
$publicKey->verify('my modified message', $signature) 
$publicKey->verify('my message', 'invalid signature') 

Alternatives #

This package aims to be very lightweight and easy to use. If you need more features, consider using of one these alternatives:

A word on the usage of RSA #

At the time of writing, RSA is secure enough for the use case we’ve built this package for.

To know more about why RSA might not be good enough for you, read this post on public-key encryption at Paragonie.com

In closing #

Spatie/crypt can also encrypt and decrypt messages. To learn more, head over to the readme of spatie/crypto on GitHub.

On our company website, you’ll find a list of packages our team has created previously. If you would like to support us, consider picking up one of our paid products or sponsoring us on GitHub.

programming

via Laravel News Links https://ift.tt/2dvygAJ

November 15, 2020 at 08:49PM

Smart camera founder gets Wyze to car prowler and uses his own tech to catch criminal in action

Smart camera founder gets Wyze to car prowler and uses his own tech to catch criminal in action

https://ift.tt/38H9CL1

When Dave Crosby, one of the co-founders of Seattle-based Wyze Labs, was the victim of a robbery this summer, he turned to his own company’s technology for help in solving the crime. A new, outdoor security camera — unreleased to the public at the time — was mounted over his driveway and captured footage of a car prowler grabbing another of the cameras from Crosby’s vehicle.

Crosby, head of marketing for the 3-year-old smart home products maker, was testing the Wyze Cam Outdoor. He ended up as a main player in a YouTube video (above) that could serve as a testimonial for the new security device.

“I actually had grabbed those Outdoor Cams from the office and put them in my car because later that week I was shooting the actual promo video for the product,” Crosby told GeekWire, admitting that he mistakenly left his car unlocked. “Little did I know that a nice promo video would be created all on its own.”

When Crosby and co-workers discovered that the thief had posted the stolen camera for sale on Craigslist the next day, he set about chronicling it all for his popular YouTube channel, to document his efforts to catch a criminal. Crosby is no slouch on YouTube — he’s got 3.25 million subscribers who usually tune in to catch the father of three singing with his daughter.

He hit the ground running that day in August — and started filming himself — when he realized his car had been broken into and the footage was on his Wyze camera. Holding up a box for the Wyze Cam Outdoor, Crosby breathlessly said, “This is brand new. No one in the world has it. People are super excited to get this … it’s gonna be huge.”

Footage from Dave Crosby’s Wyze Cam Outdoor of a man entering Crosby’s vehicle at his home. (YouTube screen grab via The Crosbys)

Crosby moved about his home that morning, informing his wife Ashley of what happened and looping in his kids, Claire, 8, Carson, 6, and June, 2. A Wyze co-worker communicated with the thief on Craigslist, trying to arrange a spot to purchase the stolen camera for $50.

Crosby talked on the phone with police, trying to figure out the best way to have them involved as he made plans to be the one who would confront the thief. He said he definitely had some safety fears as he eventually set off the next day, with his family following in another vehicle, for a Fred Meyer parking lot in Renton, Wash. He was told to just dial 911 when he was in the area and police would arrive.

“I was surprised the police wanted me to just go make a deal with him,” Crosby told GeekWire, adding that once he was on the scene about to meet the seller, police arrived instantly before he could even talk to the guy.

“It was a fun adrenaline rush and I’m glad I got to be involved in catching him,” Crosby said.

The Wyze Cam Outdoor from Seattle-based Wyze Labs. (Wyze Photo)

The video captured Crosby filling out a police report in the back of his car, seated near his kids. Footage of the suspect is blurred as he talked to police. An officer returned the stolen camera to Crosby and remarked on Wyze’s technology in relation to it’s big Amazon-owned competitor.

“Good luck with the Wyze camera,” the officer said. “Gonna compete against Ring.”

“We are. We’re gonna take ’em down,” Crosby replied. The Wyze Cam Outdoor ended up selling out instantly when it was officially released and Crosby told GeekWire that it’s been a struggle to make them as fast as the startup can.

The value of the camera ended up not being enough to book the man into jail, and Crosby said he never followed up on the results of a supposed court date for the thief.

But his kids got a lesson in crime fighting and dad came away looking pretty cool.

“You could totally be a police,” his son said in the video.

And then the promo for Wyze cameras comes full circle as his daughter concluded, “And this is why we have WyzeCams, people.”

geeky

via GeekWire https://ift.tt/2pQ6rtD

November 12, 2020 at 05:48PM

Dear Farmers, miners, Red staters,

Dear Farmers, miners, Red staters,

https://ift.tt/3eSMmuH

This is a Biden supporter.

This is what they think of you.

Please stop shipping food into Blue cities.

Please stop shipping coal and oil into Blue cities.

Let them starve in the dark.

Thank you

 

guns

via https://gunfreezone.net

November 11, 2020 at 10:35PM

How to Generate PDF and Send Email in Laravel?

How to Generate PDF and Send Email in Laravel?

https://ift.tt/36HQxpF


Hi Artisan,

In this post, we will learn laravel generate pdf and send email. if you have question about laravel mail attachment pdf then i will give simple example with solution. In this article, we will implement a dompdf send email attachment laravel. we will help you to give example of generate pdf and send mail in laravel.

you can also generate pdf and send email in laravel 6, laravel 7 and laravel 8 application.

In this example, i will simply use dompdf to generate pdf file and send mail with pdf attachment. you just need to follow few step to create simple example of send mail with created pdf file in laravel app.

Let’s see bellow steps:

Step 1: Install Laravel

I am going to explain step by step from scratch so, we need to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install dompdf Package

first of all we will install barryvdh/laravel-dompdf composer package by following composer command in your laravel 8 application.

composer require barryvdh/laravel-dompdf

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

....

Barryvdh\DomPDF\ServiceProvider::class,

],

'aliases' => [

....

'PDF' => Barryvdh\DomPDF\Facade::class,

]

Step 3: Make Configuration

In first step, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel 8 will use those sender details on email. So you can simply add as like following.

.env

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

[email protected]

MAIL_PASSWORD=rrnnucvnqlbsl

MAIL_ENCRYPTION=tls

[email protected]

MAIL_FROM_NAME="${APP_NAME}"

Step 4: Add Route

In this is step we need to create routes for items listing. so open your “routes/web.php” file and add following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PDFController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('send-email-pdf', [PDFController::class, 'index']);

Step 5: Add Controller

Here,we require to create new controller PDFController that will manage index method of route. So let’s put bellow code.

app/Http/Controllers/PDFController.php

<?php

namespace App\Http\Controllers;

use PDF;

use Mail;

class PDFController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$data["email"] = "[email protected]";

$data["title"] = "From ItSolutionStuff.com";

$data["body"] = "This is Demo";

$pdf = PDF::loadView('emails.myTestMail', $data);

Mail::send('emails.myTestMail', $data, function($message)use($data, $pdf) {

$message->to($data["email"], $data["email"])

->subject($data["title"])

->attachData($pdf->output(), "text.pdf");

});

dd('Mail sent successfully');

}

}

Step 6: Create View File

In Last step, let’s create myTestMail.blade.php(resources/views/emails/myTestMail.blade.php) for layout of pdf file and put following code:

resources/views/emails/myTestMail.blade.php

<!DOCTYPE html>

<html>

<head>

<title>ItsolutionStuff.com</title>

</head>

<body>

<h1></h1>

<p></p>

<p>Thank you</p>

</body>

</html>

Now you can run and check example.

It will send you email, let’ see.

Run Project:

php artisan serve

Open Link:

localhost:8000/send-email-pdf

Output:

I hope it can help you…

programming

via Laravel News Links https://ift.tt/2dvygAJ

November 10, 2020 at 07:42PM

There’s a Massive Recall of Amazon Ring Doorbells

There’s a Massive Recall of Amazon Ring Doorbells

https://ift.tt/36muHrq


Photo: CC Photo Labs (Shutterstock)

In a year where it seems everything is both literally and figuratively on fire, it’s not surprising that we can now add Amazon’s Ring Video Doorbell to the list. Yes, it turns out that the device you purchased and installed for the purpose of making your home safer is itself a safety hazard. As a result, Amazon has issued a massive recall of its popular doorbell/spy camera. Here’s what to know.

What’s going on with Ring Doorbells?

Amazon is recalling approximately 350,000 Ring Video Doorbells (2nd Generation) sold through Amazon.com, Ring.com, and at third-party electronics and home goods stores in the United States and Canada between June and October 2020. The company made this decision after receiving reports of 85 incidents tied to incorrectly installed doorbells—23 of which involve doorbells igniting and causing minor property damage, in addition to eight reports of minor burns.

According to the Consumer Product Safety Commission (CPSC), the video doorbell’s battery can overheat if the wrong type of screws are used to install the device, posing fire and burn hazards. As a result, the CPSC advises that consumers immediately stop installing the recalled video doorbells.

A spokesperson for Ring provided Fast Company with the following statement:

“The safety of our customers is our top priority. We [have and continue to work cooperatively with the CPSC on this issue, and] have contacted customers who purchased a Ring Video Doorbell (2nd Gen) to ensure they received the updated user manual and follow the device installation instructions. Customers do not need to return their devices.”

G/O Media may get a commission

How to know if your Ring Doorbell has been recalled

Those who use a 2nd Generation Ring Video Doorbell can enter its serial number on the Ring website to find out whether it’s part of the recall. If it turns out that yours is, download revised installation instructions and contact Ring with any questions at (800) 656-1918 from 8 a.m. to 12 a.m. ET, seven days a week, or visit the company’s website and click on “Help,” then on “Installation Services” for more information.

geeky,Tech,Database

via Lifehacker https://lifehacker.com

November 11, 2020 at 04:49PM

Learn PyQt: Laying Out Your GUIs With Qt Designer — Use Qt Designer to effortlessly build your application UI

Learn PyQt: Laying Out Your GUIs With Qt Designer — Use Qt Designer to effortlessly build your application UI

https://ift.tt/36jo1ud

When laying out your Qt GUIs it can be quite a tricky task to place every widget in the right position on your forms. Fortunately, Qt offers a set of layout managers that simplify the process of widget positioning and will allow you to easily create any kind of layout. To lay out the widget in a form, you can create everything in code, or you can create your layout with Qt Designer. In this tutorial, you’ll learn how to use Qt’s layouts with Qt Designer to build complex GUIs for your applications.

Additionally, we’ll create a dialog example using several widgets with a coherent layout to reinforce your knowledge and put everything together into a fully functional dialog just like you would create in a real-world application.

Using Layouts With Qt Designer

Qt Designer is the Qt tool for designing and creating graphical user interfaces (GUI) for desktop applications. With Qt Designer, you can create windows, dialogs, and forms. It allows you to add different kind of widgets to create your GUIs using on-screen forms and a drag-and-drop based interface.

Qt Designer’s main interface looks as follows —

Qt Designer — Main Interface
Qt Designer — Main Interface

Qt Designer has a clear and user-friendly interface that allows you to create any kind of GUI by dragging widget onto an empty form. After you place all the widgets on your form, you need to place them in a coherent layout. This will ensure that all your widgets will be displayed and resized properly when the form is previewed or used in an application.

Qt’s layout managers are structured containers which automatically arrange child widgets ensuring that they make good use of the available space. Placing widgets within a layout manager automatically lays them out according to the defined rules. One of Qt Designer’s most useful features is the ability to drag and drop hierarchies of layout managers to arrange widgets into clean and functional interfaces.

In Qt Designer, you can create layout objects by applying a layout to a group of existing widgets. Although it’s possible to drag layouts onto a form and then drag widgets into the layouts, this can be a bit fiddly. The best practice is to instead drag all the widgets and spacers you need onto the form and then select related widgets and spacers and apply the layouts to them. Use the following steps —

  1. Drag and drop the widgets on the form trying to place them near their desired position
  2. Select the widgets that should be managed with a given layout, by holding the Ctrl key and clicking on them
  3. Apply the appropriate layout (horizontal, vertical, grid, or form) using Qt Designer’s toolbar, main menu, or the form’s context menu

Before you go into an example, take a look at the layout related options that Qt Designer offers —

  1. Use layout options on the main toolbar
  2. Use layout options on the main menu
  3. Use layout options on the form’s context menu

The most accessible way for creating layouts is using the layout section of Qt Designer’s main toolbar. This section looks as follows —

Qt Designer — Layout toolbar
Qt Designer — Layout toolbar

From left to right, you’ll find the following buttons —

  • Lay Out Horizontally arranges selected widgets in a horizontal layout next to each other (Key combination, Ctrl+1). This option uses a standard QHBoxLayout object
  • Lay Out Vertically arranges selected widgets in a vertical layout, one below another (key combination, Ctrl+2). This option uses a standard QVBoxLayout object
  • Lay Out Horizontally in Splitter arranges the widgets horizontally using a splitter (Key combination, Ctrl+3)
  • Lay Out Vertically in Splitter arranges the widgets vertically using a splitter (Key combination, Ctrl+4)
  • Lay Out in a Grid arranges widgets in a table-like grid (rows and columns). By default, each widget occupies one cell of the grid, but you can modify this behavior and make the widgets to span several cells (Key combination, Ctrl+5). This option uses a standard QGridLayout object
  • Lay Out in a Form Layout arranges selected widgets in a two-column layout. The left column is usually for labels asking for some information and the right column includes widgets for entering, editing, or showing that information (Key combination, Ctrl+6)
  • Break Layout this key allows you to brake an existing layout. Once widgets are arranged in a layout, you cannot move and resize them individually, because their geometry is controlled by the layout. To modify individual widgets, you’ll need to break the layout and redo it later (Key combination Ctrl+0)
  • Adjust Size adjusts the size of the layout to accommodate contained widgets and to ensure that each has enough space to be visible (Key combination Ctrl+J)

These same layout related options are also available through Qt Designer’s main menu under the Form menu and through the form’s context menu, so you can choose the one you like better.

Now we have the theory out of the way, we can put these layouts into practise. In the next few sections, we’ll be using Qt Designer to lay out the widgets on our forms and build nice and elegant GUIs for your desktop applications. But before we start experimenting with the different layout managers that Qt offers, we’re first going to create a custom widget to visualize the layouts as we go through this tutorial.

The completed .ui file can be downloaded below if you would like to skip this step.

layout-labels.ui

Go ahead and fire up your Qt Designer, then run the following steps —

  1. Select Widget at the templates/forms tab of the New Form dialog. This will create a new empty form to work on.
  2. Save your form as layout-labels.ui.
  3. Look for a Label widget on the Widget Box and drag it onto the form.
  4. Go to the Property Editor and set the text property to 0.
  5. Open the Text Edit dialog and set the text color to white. Set the font size to 20 points and justify the text. Press OK to apply the changes.
  6. Go to the Property Editor and set the autoFillBackground property to True by selecting the check box.
  7. Look up the palette property and open the Edit Palette dialog. Use the Quick option to set the color to red.

If you feel lost, take a look at the following screencast to see the steps in action —

In this example, you create a new window based on the Widget template. Then, you add a Label, set its text property to 0, and set its background color to red.

To complete this example, repeat all the steps to add three more labels with their respective text set to 1, 2, and 3 and their colors set to green, yellow, and blue. You’ll end up with a form like this:

Qt Designer — Form with colored labels
Qt Designer — Form with colored labels

The above screenshot shows the initial form that you’ll use for the next few sections. It’s a clean form with four label objects on it. You can set a background color to each label to be able to see and differentiate them more easily in the following sections.

Horizontal Layouts, QHBoxLayout

You can use a horizontal layout manager (QHBoxLayout) to arrange the widgets in one row. To create this kind of layout in code, you need to instantiate the QHBoxLayout class and then add your widgets to the layout object. In Qt Designer it’s easier to work in the other way around.

With your layout-labels.ui file open, first select all your labels. To do this, you can click each widget in turn while you hold the Ctrl key or you can also click and drag with the mouse pointer inside the form to select the widgets.

Once you have selected the widgets, put them in a horizontal layout by selecting the Lay Out Horizontally button in the Qt Designer’s main toolbar. You can also use the option Lay out->Lay Out Horizontally from the context menu shown below or you can press Ctrl+1. The following screencast will guide you through these steps —

If the layout is wrong, then you can easily undo everything and restart laying things out again. To undo things, you can press Ctrl+z or use the Edit menu from Qt Designer’s main menubar. If that isn’t possible or doesn’t work, then you can just break the layout using the Break Layout button from Qt Designer’s main toolbar. Another way to break a layout is to press Ctrl+0 or choose Break Layout from the form’s context menu.

Vertical Layouts, QVBoxLayout

You can use a vertical layout (QVBoxLayout) to arrange your widgets in one column one above the other. This can be very useful when you’re creating groups of widgets and you need to ensure that they are vertically aligned.

Starting up with your original layout-labels.ui file, the first step will be to select the widgets that you need to include in the vertical layout. After that, you can click on the Lay Out Vertically button over the main toolbar, or you can use the context menu, or you can also press Ctrl+2. The following screencast will guide you through these steps —

If you take a closer look at the screencast, then you can see that the layout object is indicated by a thin red frame surrounding the labels on the form. This red frame isn’t visible at preview or at runtime it’s just a guide you can use when you’re designing the form. Also notices that, the layout object appears in the Object Inspector and its properties (margins and constraints) are shown in the Property Editor.

Grid Layouts, QGridLayout

Sometimes you need to lay out your widgets both horizontally and vertically within the same layout. To do this, you can use a grid layout manager (QGridLayout). Grid layout managers lay out your widgets in a square or rectangular grid, with all widgets aligning vertically and horizontally with their neighbours. This kind of layout can give you much more freedom to arrange your widgets on a form, while maintaining some degree of structure. This arrangement can be more suitable than nested arrangement of horizontal and vertical layouts, particularly when you care about the alignment of adjacent rows or columns.

You can build a grid layout with Qt Designer in the same way as for other layouts. The first step is to select the group of widgets that you want to lay out using a grid layout manager. Then, you can use the toolbar, the context menu, or you can press Ctrl+5 to set up the layout. Watch the following screencast —

In this case, we use a 2 x 2 grid layout to arrange the labels on your form. Notice that, to use this kind of layout, you should first place your widgets in rows and columns on the form, as shown in the screencast above. Qt Designer is quite clever and will try to keep your design as similar as possible to what you initially created by hand. It can even create difficult multi-column arrangements automatically or automatically fill empty cells.

Form Layouts, QFormLayout

While a QGridLayout can be used to layout forms with inputs and labels in two columns, Qt also provides a layout designed specifically for this purpose — (QFormLayout). This type of layout is ideal when you’re creating a structured data-entry or database application. The left column will commonly hold labels that ask for some information. The right column holds the input widgets such as line edits (QLineEdit), spin boxes (QSpinBox), date edits (QDateEdit), combo boxes (QComboBox), and so on.

The advantage of using this layout over QGridLayout is that it is simpler to work with when you only need two columns. The following screencast shows it in action —

In this example, we first add four new labels. These labels will hold information about the data you need to be entered or edited in the second column. In this case, the second column holds your tests colored labels, but usually this column will be used to place input widget like line edits, spin boxes, combo boxes, and so on.

Splitter Layouts

Splitters are container objects that arrange widgets horizontally or vertically in two resizeable panels. With this kind of layout, you can freely adjust the amount of space that each panel occupy on your form, while keeping the total space used constant. In Qt splitter layouts are managed using QSplitter.

Even though splitters are technically a container widget (not a layout), Qt Designer treats them as layouts that can be applied to existing widgets. To place a group of widgets into a splitter, you first select them as usually and then apply the splitter by using the appropriate toolbar button, keyboard shortcut, or context menu option in Qt Designer Take a look at the following screencast —

In this example, we first apply a horizontal splitter to your labels. Notice that, you’ll need to launch the form preview if you want to see the splitter in action. You can launch the form preview by pressing Ctrl+R. Later on, we apply a vertical splitter to the labels. In each case, you can freely resize the widget using your mouse’s pointer.

Building Other Layouts With Qt Designer

There are a few more things you can do with layouts in Qt Designer. For example, suppose you need to add a new widget to an existing layout, or to use nested layouts to arrange your widgets in a complex GUI. In the following few sections, we’ll cover how to accomplish some of these tasks.

Inserting Objects into an Existing Layout

Objects can be inserted into an existing layout by dragging them from their current positions and dropping them at the required position in the layout. A blue cursor is displayed in the layout when an object is dragged over it to indicate where the object will be placed.

Take a look at the following screencast where we put three of our labels in a vertical layout and then realize the we left the blue label out of the game —

It’s also possible to move or change the position of a given widget in a layout. To do this, just drag and drop the widget to its new position in the layout. Remember to follow the blue line to get this right.

Nesting Layouts to Build Complex GUIs

You can also nest layout managers one inside another using Qt Designer. The inner layout then becomes a child of the enclosing layout. By doing this you can iteratively create very complex, yet well-structured user interfaces.

Layouts can be nested as deep as you need. For example, to create a dialog with a horizontal row of buttons at the bottom and a bunch of other widgets aligned vertically on the form, you can use a horizontal layout for the buttons and a vertical layout for the rest of the widgets, then wrap these layouts in a vertical layout.

Coming back to our colored labels example, the following screencast shows the process of arranging a nested layout in Qt Designer —

In this example, we first arrange widgets in pair using a horizontal layout. Then we nest both of these layouts in a third layout, but this time a vertical one. The layouts can be nested as deep as required.

When you select a child layout, its parent layout can be selected by pressing the Shift key while clicking on it. This allows you to quickly select a specific layout in a hierarchy, which otherwise will be difficult to do because of the small frame delimiting each layout manager.

Setting a Top Level or Main Layout

The final step you need to perform when building a form is to combine all the layouts and widget into one main layout or top level layout. This layout is at the top of the hierarchy of all other layouts and widgets. It’s vital that you have a layout because otherwise the widgets on your form won’t resize when you resize the window.

To set the main layout just right click anywhere on your form that doesn’t contain a widget or layout. Then, you can select Lay Out Horizontally, or Lay Out Horizontally, or you can also select Lay Out in a Grid like in the following screencast —

In this example, we use each of the three different layouts as our top level layout in turn. We first use a horizontal layout, then break the layout and use a vertical layout. Finally we set a grid layout. Which top level layout you choose for your top-level layout will depend on your specific requirements for your app.

It’s important that you note that top level layouts are not visible as a separate object in the Object Inspector. Its properties appear below the widget properties of the main form. Also, note that if your form doesn’t have a layout, then its icon appears with a red circle on the Object Inspector. Another way to check if you’ve properly set a main layout is trying to resize the form, if a main layout is in place, then your widgets should resize accordingly.

As you start to build more complex applications, you’ll discover that other container widgets also require you to set a top level layout, for example QGroupBox, QTabWidget, QToolBox, and so on. To do this, you can run the same steps you’ve seen here, but this time you need to right click on the container widget.

Laying Out a Dialog With Qt Designer

For a final and more complete example of how to use layouts with Qt Designer, we’re now going to create a dialog to introduce some information in a database application. Suppose we’re building a Human Resources Management software for our company Poyqote Inc.. We’re now working in a form to introduce some data about our employees. The dialog should present users with a user-friendly GUI for introducing the following data:

  • Employee name
  • Employment date
  • Department
  • Position
  • Annual salary
  • Job description

What is the best way to lay out this form? There are many options, and it’s largely a matter of taste and practise. But here we’re using a QFormLayout to arrange the entry fields into two columns with labels on the left and input boxes on the right. The process of creating the layout is shown in the following screencast — 

The base dialog is created using Qt Designer’s Dialog with Buttons Bottom template. Then, we add some labels and some input widget, including line edits, date edits, text edits, and combo boxes. Next we put all those widgets in a form layout and finally define a top level or main layout for the form.

The finished dialog .ui file can be downloaded here.

Conclusion

Qt Designer is a powerful tool when it comes to creating GUIs using Qt. One of its most straightforward and useful features is the ability to arrange your widgets in different types of layouts. Learning how to effectively create layouts with Qt Designer can sky rocket your productivity, particularly when creating complex GUIs.

This tutorial guided you through the process of creating custom layouts with Qt Designer. You now know how to get the most out of Qt Designer when laying out your GUIs.

Python

via Planet Python https://ift.tt/1dar6IN

November 10, 2020 at 05:48AM