Qt for Python Tutorial SimpleDialog: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
mNo edit summary
 
(4 intermediate revisions by 3 users not shown)
Line 1: Line 1:
== Creating a simple PySide2 dialog application ==


In this tutorial we will show how to build a simple dialog with some basic widgets.
The idea is that the user inserts his name in a QLineEdit, clicks a QPushButton and sees greetings.


[[Category:LanguageBindings::PySide]]
Let us just start with a simple stub which creates and shows a dialog.
 
This stub will be updated in the course of this tutorial but you can use this stub to your own PySide2 projects if you need to.
'''English''' [[PySideTutorials_Simple_Dialog_Japanese|日本語]]
 
= Creating a simple PySide dialog application =
 
In this tutorial we will show how to build a simple dialog with some basic widgets. The idea is that the user inserts his name in a QLineEdit, clicks a QPushButton and sees greetings.
 
Let us just start with a simple stub which creates and shows a dialog. This stub will be updated in the course of this tutorial but you can use this stub to your own PySide projects if you need to.
 
<code>
#!/usr/bin/python
# -'''- coding: utf-8 -'''-


<syntaxhighlight lang="python" line='line'>
import sys
import sys
from PySide.QtCore import *
from PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton
from PySide.QtGui import *


class Form(QDialog):
class Form(QDialog):


def __init__(self, parent=None):
    def __init__(self, parent=None):
super(Form, self).__init__(parent)
        super(Form, self).__init__(parent)
self.setWindowTitle("My Form")
        self.setWindowTitle("My Form")




if __name__ == '__main__':
if __name__ == '__main__':
# Create the Qt Application
    # Create the Qt Application
app = QApplication(sys.argv)
    app = QApplication(sys.argv)
# Create and show the form
    # Create and show the form
form = Form()
    form = Form()
form.show()
    form.show()
# Run the main Qt loop
    # Run the main Qt loop
sys.exit(app.exec_())
    sys.exit(app.exec_())
</code>
</syntaxhighlight>


If you have followed the previous tutorials, you are already familiar with a lot of the code here. The imports aren't new to you, the same for the creation of the QApplication and the execution of the Qt main loop. The only novelty here is the class definition.
The imports aren't new to you, the same for the creation of the QApplication and the execution of the Qt main loop.
The only novelty here is the class definition.


You can create any class which subclasses PySide widgets. In this case, we are just subclassing the QDialog to do our custom dialog which we've called "Form". We have also implemented the ''init''() method which calls the QDialog init method with the parent widget, if any. Also new, is the '''setWindowTitle()''' which just sets the title of the dialog window. Also, in ''main''(), you can see that we are creating a Form object, and showing it to the world.
You can create any class which subclasses PySide2 widgets.
In this case, we are just subclassing the QDialog to do our custom dialog which we've called "Form".
We have also implemented the '''init'''() method which calls the QDialog init method with the parent widget, if any.
Also new, is the '''setWindowTitle()''' which just sets the title of the dialog window.
Also, in '''main'''(), you can see that we are creating a Form object, and showing it to the world.


== Create the widgets ==
== Create the widgets ==
We are going to create two widgets- a QLineEdit where the user can insert his name, and a QPushButton which we will use to print the contents of the QLineEdit. So, we are going to add the following code to the'''''init''()* method of our Form:
We are going to create two widgets a QLineEdit where the user can insert his name, and a QPushButton which we will use to print the contents of the QLineEdit.
So, we are going to add the following code to the '''init'''() method of our Form:


<code>
<syntaxhighlight lang="python" line='line'>
# Create widgets
# Create widgets
self.edit = QLineEdit("Write my name here..")
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")
self.button = QPushButton("Show Greetings")
</code>
</syntaxhighlight>


As should be intuitive by now, both widgets will show the corresponding texts.
As should be intuitive by now, both widgets will show the corresponding texts.


== Create a layout to organize the widgets ==
== Create a layout to organize the widgets ==
Qt comes with some layouts which helps the user on the organization of his widgets on an application. In this case, we will make it simple and create a QVBoxLayout which will distribute the widgets vertically. The following code will be added also to the '''''init''()''' method, after the creation of the widgets:
Qt comes with some layouts which helps the user on the organization of his widgets on an application.
In this case, we will make it simple and create a QVBoxLayout which will distribute the widgets vertically.
The following code will be added also to the '''init'''() method, after the creation of the widgets:


<code>
<syntaxhighlight lang="python" line='line'>
# Create layout and add widgets
# Create layout and add widgets
layout = QVBoxLayout()
layout = QVBoxLayout()
Line 61: Line 61:
# Set dialog layout
# Set dialog layout
self.setLayout(layout)
self.setLayout(layout)
</code>
</syntaxhighlight>


So, we create the layout, add the widgets with '''addWidget()''', and finally we say that our Form will have our QVBoxLayout as its layout.
So, we create the layout, add the widgets with '''addWidget()''', and finally we say that our Form will have our QVBoxLayout as its layout.


== Create the function to greet and connect the button ==
== Create the function to greet and connect the button ==
Finally, we just have to add a function to our custom Form- the one which will greet the user - and connect our button to it. Our function will be a part of the Form, so you have to add it after the '''''init''()''' function:
Finally, we just have to add a function to our custom Form- the one which will greet the user - and connect our button to it.
Our function will be a part of the Form, so you have to add it after the '''init'''() function:


<code>
<syntaxhighlight lang="python" line='line'>
# Greets the user
# Greets the user
def greetings(self):
def greetings(self):
print ("Hello s" self.edit.text())
    print ("Hello {}".format(self.edit.text()))
</code>
</syntaxhighlight>


Our function just writes the contents of the QLineEdit to the python console. We have access to the text by means of the '''QLineEdit.text()''' method.
Our function just writes the contents of the QLineEdit to the python console.
We have access to the text by means of the '''QLineEdit.text()''' method.


Now that we have everything, we just need to connect the QPushButton to the '''Form.greetings()''' method. In the '''''init''()''' method we just need to add:
Now that we have everything, we just need to connect the QPushButton to the '''Form.greetings()''' method.
In the '''init'''() method we just need to add:


<code>
<syntaxhighlight lang="python" line='line'>
# Add button signal to greetings slot
# Add button signal to greetings slot
self.button.clicked.connect(self.greetings)
self.button.clicked.connect(self.greetings)
</code>
</syntaxhighlight>


Once executed, you can insert your name in the QLineEdit and watch the console for greetings.
Once executed, you can insert your name in the QLineEdit and watch the console for greetings.
=== Things you can do: ===
* Instead of showing your name in the python console, can you show your name in a popup message box? Check the detailed description of QMessageBox in the [http://www.pyside.org/docs/pyside/PySide/QtGui/QMessageBox.html PySide online reference]
* Can you add a Icon to the window? Check the description of QWidget in the [http://www.pyside.org/docs/pyside/PySide/QtGui/QWidget.html PySide online reference]
* What about adding a button to close? Just create a new button, add it to the layout and connect it to the '''exit''' slot.
* You can also change the layout to horizontal! You do it with QHBoxLayout. Check other layouts in the [http://www.pyside.org/docs/pyside/PySide/QtGui/index.html PySide online reference] such as '''QHBoxLayout''', '''QGridLayout''' among others.


== Full Code ==
== Full Code ==
Line 96: Line 92:
Here is the full code for this tutorial:
Here is the full code for this tutorial:


<code>
<syntaxhighlight lang="python" line='line'>
#!/usr/bin/python
#!/usr/bin/python
# -'''- coding: utf-8 -'''-
# -'''- coding: utf-8 -'''-


import sys
import sys
from PySide.QtCore import *
from PySide2.QtWidgets import (QLineEdit, QPushButton, QApplication,
from PySide.QtGui import *
    QVBoxLayout, QDialog)


class Form(QDialog):
class Form(QDialog):


def ''init''(self, parent=None):
    def __init__(self, parent=None):
super(Form, self).''init''(parent)
        super(Form, self).__init__(parent)
# Create widgets
        # Create widgets
self.edit = QLineEdit("Write my name here")
        self.edit = QLineEdit("Write my name here")
self.button = QPushButton("Show Greetings")
        self.button = QPushButton("Show Greetings")
# Create layout and add widgets
        # Create layout and add widgets
layout = QVBoxLayout()
        layout = QVBoxLayout()
layout.addWidget(self.edit)
        layout.addWidget(self.edit)
layout.addWidget(self.button)
        layout.addWidget(self.button)
# Set dialog layout
        # Set dialog layout
self.setLayout(layout)
        self.setLayout(layout)
# Add button signal to greetings slot
        # Add button signal to greetings slot
self.button.clicked.connect(self.greetings)
        self.button.clicked.connect(self.greetings)


# Greets the user
    # Greets the user
def greetings(self):
    def greetings(self):
print ("Hello s" self.edit.text())
        print ("Hello %s" % self.edit.text())


if ''name'' == '''main''':
if __name__ == '__main__':
# Create the Qt Application
    # Create the Qt Application
app = QApplication(sys.argv)
    app = QApplication(sys.argv)
# Create and show the form
    # Create and show the form
form = Form()
    form = Form()
form.show()
    form.show()
# Run the main Qt loop
    # Run the main Qt loop
sys.exit(app.exec_())
    sys.exit(app.exec_())
</syntaxhighlight>

Latest revision as of 08:56, 18 April 2018

Creating a simple PySide2 dialog application

In this tutorial we will show how to build a simple dialog with some basic widgets. The idea is that the user inserts his name in a QLineEdit, clicks a QPushButton and sees greetings.

Let us just start with a simple stub which creates and shows a dialog. This stub will be updated in the course of this tutorial but you can use this stub to your own PySide2 projects if you need to.

import sys
from PySide2.QtWidgets import QApplication, QDialog, QLineEdit, QPushButton

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("My Form")


if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())

The imports aren't new to you, the same for the creation of the QApplication and the execution of the Qt main loop. The only novelty here is the class definition.

You can create any class which subclasses PySide2 widgets. In this case, we are just subclassing the QDialog to do our custom dialog which we've called "Form". We have also implemented the init() method which calls the QDialog init method with the parent widget, if any. Also new, is the setWindowTitle() which just sets the title of the dialog window. Also, in main(), you can see that we are creating a Form object, and showing it to the world.

Create the widgets

We are going to create two widgets a QLineEdit where the user can insert his name, and a QPushButton which we will use to print the contents of the QLineEdit. So, we are going to add the following code to the init() method of our Form:

# Create widgets
self.edit = QLineEdit("Write my name here..")
self.button = QPushButton("Show Greetings")

As should be intuitive by now, both widgets will show the corresponding texts.

Create a layout to organize the widgets

Qt comes with some layouts which helps the user on the organization of his widgets on an application. In this case, we will make it simple and create a QVBoxLayout which will distribute the widgets vertically. The following code will be added also to the init() method, after the creation of the widgets:

# Create layout and add widgets
layout = QVBoxLayout()
layout.addWidget(self.edit)
layout.addWidget(self.button)
# Set dialog layout
self.setLayout(layout)

So, we create the layout, add the widgets with addWidget(), and finally we say that our Form will have our QVBoxLayout as its layout.

Create the function to greet and connect the button

Finally, we just have to add a function to our custom Form- the one which will greet the user - and connect our button to it. Our function will be a part of the Form, so you have to add it after the init() function:

# Greets the user
def greetings(self):
    print ("Hello {}".format(self.edit.text()))

Our function just writes the contents of the QLineEdit to the python console. We have access to the text by means of the QLineEdit.text() method.

Now that we have everything, we just need to connect the QPushButton to the Form.greetings() method. In the init() method we just need to add:

# Add button signal to greetings slot
self.button.clicked.connect(self.greetings)

Once executed, you can insert your name in the QLineEdit and watch the console for greetings.

Full Code

Here is the full code for this tutorial:

#!/usr/bin/python
# -'''- coding: utf-8 -'''-

import sys
from PySide2.QtWidgets import (QLineEdit, QPushButton, QApplication,
    QVBoxLayout, QDialog)

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        # Create widgets
        self.edit = QLineEdit("Write my name here")
        self.button = QPushButton("Show Greetings")
        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        # Set dialog layout
        self.setLayout(layout)
        # Add button signal to greetings slot
        self.button.clicked.connect(self.greetings)

    # Greets the user
    def greetings(self):
        print ("Hello %s" % self.edit.text())

if __name__ == '__main__':
    # Create the Qt Application
    app = QApplication(sys.argv)
    # Create and show the form
    form = Form()
    form.show()
    # Run the main Qt loop
    sys.exit(app.exec_())