PySide——Python图形化界面入门教程(二)

PySide——Python图形化界面入门教程(二)

                ——交互Widget和布局容器

               ——Interactive Widgets and Layout Containers

翻译自:http://pythoncentral.io/pyside-pyqt-tutorial-interactive-widgets-and-layout-containers/

上一个教程中,我们了解了一些QWidget提供的功能,还有一个特殊的子类QLabel。更进一步的,我们完成了一个用来说明简单Python/Qt应用的例子。但是,我们掌握的远远不能满足用户的需求,因为我们只能给他们显示文本,我们的应用只会唱独角戏!我们需要一些方法让用户可以和我们的程序交互,让独角戏变成二人转。Qt提供了丰富的交互式widgets,这里我们将要学习其中的一小部分;我们将使用他们体验如何在图形化(form)上布置widgets。下一个教程,我们将学习如何使用信号和槽来响应用户的交互。

 

交互式Widgets

Python/Qt有一系列的widgets,可以非常简单的实现与用户交互,并且容易和你的应用逻辑联系。

 

按钮(Buttons)

一个最简单的交互方式就是让用户点击按钮,Qt中就是QPushButton。QPushButton构造器有三个结构:

1 QPushButton(parent=None)
2 QPushButton(text, [parent=None])
3 QPushButton(icon, text, [parent=None])

parent参数是一个QWidget,text是一个Python string或unicode,icon是一个QIcon。创建一个被some-form拥有的带有文字“Go”的按钮,可以这样:

go_button = QPushButton('Go', some_form)

如果我们想为按钮设置一个键盘快捷键,如Alt-G,我们可以在‘Go’前添加一个‘&G’:

go_button = QPushButton('&Go', some_form)

这还有一些按钮的其他功能,还拿go_button做例子,你可以将其设置为form的默认按键:

go_button.setDefault(True)

还可以设置成平的:

go_button.setFlat(True)

将False传递到方法中会有相反的作用。一个按钮还可以在被点击时弹出一个菜单(menu):传递一个QMenu对象给按钮的setMenu方法。(我们以后再研究菜单)

 

文本框(Textboxes)

 Qt的文本框控件是QLineEdit;它允许用户输入编辑单行的简单文本,其构造器有如下两种:

1 QLineEdit(parent=None)
2 QLineEdit(text, [parent=None])

他们的不同就是第二个允许用text参数设置包含的文本。QLineEdit对象有许多的方法,但是我们只关心几个最基本的。你可以使用text()方法取回文本,用setText(text)设置文本,使用setMaxLength(chars)设置最大可输入长度。它可以通过setReadOnly(True)设置为只读的,使用setPlaceholderText(text)设置占位文字(placeholder text,就是那种你输入前提示说明的字)。QLineEdit还有更多的高级属性:可以设置输入过滤器,处理选择和输入历史等等。

 

组合框(Comboboxes)

QComboBox widget是用来给用户提供多个文本或文本/图标的选择,用户必须选择其一。(多项选择参见QListView和QListWidget)它的构造器如下:

1 QComboBox(parent)

它的构造如此简单,但是目前还没有任何选项。你可以用多种方式添加选项。如果你的所有选项都是文字的,你可以使用addItems(texts),texts是字符串列表。一个一个的添加选项可以使用addItem,它有两个有效的方式

1 addItem(icon, text, [userData=None])
2 addItem(text, [userData=None])

参数icon是QIcon,text是一个unicode对象,userData是任何对象。你可以使用insertItem插入选项:

1 insertItem(index, icon, text, [userData=None])
2 insertItem(index, text, [userData=None])

QComboBox是一个灵活的widget,用它还可以做更多的事情。

 

例子程序:总览

接下来,我们将学习如何把小部件组合成一个表单布局,但在我们可以做到这一点之前,让我们先看一下这个示例应用程序。

 《PySide——Python图形化界面入门教程(二)》

正如你所看到的,这是一个非常简单的应用程序。用户可以选择一个称呼和进入的人的姓名(或其他单位)他们要打招呼,当他们点击“建立问候,问候将在窗体上显示一个标签。

 

布局管理(Layout Management)

PySide和PyQt有两个可用的方法来管理布局:使用绝对位置,开发者必须明确设置每个widget和位置和大小;使用的布局容器(layout containers),自动安排位置和调整大小。我们将用两种方法构建上面提到的例子程序。

 

绝对位置

去设置widget的无力位置,你需要使用widget的move(x, y)方法;x和y是水平和垂直距离,这个距离是从外框(form)的左上角到widget的左上角。这是我们使用绝对距离创建的外形:

 1 # Every Qt application must have one and only one QApplication object;
 2 # it receives the command line arguments passed to the script, as they
 3 # can be used to customize the application's appearance and behavior
 4 qt_app = QApplication(sys.argv)
 5  
 6 class AbsolutePositioningExample(QWidget):
 7     ''' An example of PySide absolute positioning; the main window
 8         inherits from QWidget, a convenient widget for an empty window. '''
 9     def __init__(self):
10         # Initialize the object as a QWidget
11         QWidget.__init__(self)
12  
13         # We have to set the size of the main window
14         # ourselves, since we control the entire layout
15         self.setMinimumSize(400, 185)
16         self.setWindowTitle('Dynamic Greeter')
17  
18         # Create the controls with this object as their parent and set
19         # their position individually; each row is a label followed by
20         # another control
21  
22         # Label for the salutation chooser
23         self.salutation_lbl = QLabel('Salutation:', self)
24         self.salutation_lbl.move(5, 5) # offset the first control 5px
25                                        # from top and left
26         self.salutations = ['Ahoy',
27                             'Good day',
28                             'Hello',
29                             'Heyo',
30                             'Hi',
31                             'Salutations',
32                             'Wassup',
33                             'Yo']
34         # Create and fill the combo box to choose the salutation
35         self.salutation = QComboBox(self)
36         self.salutation.addItems(self.salutations)
37  
38         # Allow 100px for the label and 5px each for borders at the
39         # far left, between the label and the combobox, and at the far
40         # right
41         self.salutation.setMinimumWidth(285)
42         # Place it five pixels to the right of the end of the label
43         self.salutation.move(110, 5)
44  
45         # The label for the recipient control
46         self.recipient_lbl = QLabel('Recipient:', self)
47         # 5 pixel indent, 25 pixels lower than last pair of widgets
48         self.recipient_lbl.move(5, 30)
49  
50         # The recipient control is an entry textbox
51         self.recipient = QLineEdit(self)
52         # Add some ghost text to indicate what sort of thing to enter
53         self.recipient.setPlaceholderText('world' or 'Matey')
54         # Same width as the salutation
55         self.recipient.setMinimumWidth(285)
56         # Same indent as salutation but 25 pixels lower
57         self.recipient.move(110, 30)
58  
59         # The label for the greeting widget
60         self.greeting_lbl = QLabel('Greeting:', self)
61         # Same indent as the others, but 45 pixels lower so it has
62         # physical separation, indicating difference of function
63         self.greeting_lbl.move(5, 75)
64  
65         # The greeting widget is also a label
66         self.greeting = QLabel('', self)
67         # Same indent as the other controls
68         self.greeting.move(110, 75)
69  
70         # The build button is a push button
71         self.build_button = QPushButton('&Build Greeting', self)
72  
73         # Place it at the bottom right, narrower than
74         # the other interactive widgets
75         self.build_button.setMinimumWidth(145)
76         self.build_button.move(250, 150)
77  
78     def run(self):
79         # Show the form
80         self.show()
81         # Run the Qt application
82         qt_app.exec_()
83  
84 # Create an instance of the application window and run it
85 app = AbsolutePositioningExample()
86 app.run()

不用说,一个大型的应用程序可能会变得非常麻烦。另外,它也没有大小改变的反应;标签只是坐在指定的位置。不仅如此,想象一下,如果有视觉障碍的用户想把他们的字体设置的大一些;使用固定的位置,您设置的控件将不再适当。

 

布局容器(Layout Containers)

由于上述种种原因,布局容器比绝对位置更为常用,他们更加灵活,替程序员分担了计算确切位置的任务,并且他们可以调整布局去适应不同平台的GUI设置,如GTK+, KDE, Mac OS X等等。这有5个主要的布局容器,他们都是继承自QLayout:

  • QHBoxLayout
  • QVBoxLayout
  • QGridLayout
  • QStackedLayout
  • QFormLayout

他们用来满足不同的需求。简而言之,QHBoxLayout和QVBoxLayout将widgets一个挨一个的水平(horizontally)、垂直(vertically)排列;QGridLayout可按照任意大小表格布局;QStackedLayout将他们一个放在一个的上面(就像stack栈一样);QFormLayout是一个特殊的两栏布局,它提供特殊的方法用标签安排内容在第一列,在第二列安排相关的空间。这些布局非常有用,但是你的布局选项不局限于他们,你可以将布局嵌套组合来创建更复杂易用的用户接口。现在,我们来看看水平、垂直布局和QFormLayout。

 

QVBoxLayout和QHBoxLayout

盒子布局(box layouts)非常的直截了当。使用它作为最上层的布局,创建布局非常简单——它的构造器需要任何参数——并且使用望名知义的方法addWidget来添加widget。接下来你就可以设置它所属的窗口。例如:

 1 win = QWidget()
 2  
 3 # The three labels
 4 lbl_1 = QLabel("We're")
 5 lbl_2 = QLabel('stacked')
 6 lbl_3 = QLabel('up.')
 7  
 8 # A vertical box layout
 9 layout = QVBoxLayout()
10  
11 # Add the widgets to the layout
12 layout.addWidget(lbl_1)
13 layout.addWidget(lbl_2)
14 layout.addWidget(lbl_3)
15  
16 # Set layout as the layout for the window
17 win.setLayout(layout)

QHBoxLayout也可以被同样使用,尽管它不常作为最上层的布局。它常常被作为子布局。为一个布局中添加另一个布局,使用该布局容器的addLayout方法,例如:

1 layout = QVBoxLayout()
2 sub_layout = QHBoxLayout()
3  
4 # ... Fill the layouts with widgets ...
5  
6 layout.addLayout(sub_layout)

盒子布局有另一个更重要并且常用的方法:addStretch。一个常见的布局有很多的控件,他们之间具有灵活的空间。为了完成这个目的,在盒子的开始添加widgets,然后添加一个设置大于0的空闲空间,layout.addStretch(1),然后再添加剩下的widgets。

 

QFormLayout

QFormLayout非常像QVBoxLayout,但是它可以不用创建子布局就轻松的将每一行分成两列。这通过使用外观布局的addRow方法,它有很多重载(overloaded?)。单参数的版本:

1 addRow(QWidget)
2 addRow(QLayout)

添加widget或布局在整个QFormLayout的最后。双参数版本:

1 unicode, QLayout
2 unicode, QWidget
3 QWidget, QWidget
4 QWidget, QLayout

作为一个“标签”在第一列中初始化元素,第二个是第二列。unicode参数作为QLabel的文本,QWidget可以是任意的widget。

 

盒子布局的例子(Box Layout Example)

现在我们已经了解了如何创建交互式widget和用灵活的布局管理他们,现在我们重新创建例子应用。我们窗口的主布局是QVBoxLayout,它有两个子布局,一个QformLayout包含所有的标签控件,和一个QHBoxLayout来管理右下角的按钮位置。我们将使用addStretch来分离QFormLayout,并且把按钮挤到QHBoxLayout的右边。你会注意到,许多代码同绝对位置版本是一样的;比如,创建单独控件的时候。

 1 qt_app = QApplication(sys.argv)
 2  
 3 class LayoutExample(QWidget):
 4     ''' An example of PySide/PyQt absolute positioning; the main window
 5         inherits from QWidget, a convenient widget for an empty window. '''
 6  
 7     def __init__(self):
 8         # Initialize the object as a QWidget and
 9         # set its title and minimum width
10         QWidget.__init__(self)
11         self.setWindowTitle('Dynamic Greeter')
12         self.setMinimumWidth(400)
13  
14         # Create the QVBoxLayout that lays out the whole form
15         self.layout = QVBoxLayout()
16  
17         # Create the form layout that manages the labeled controls
18         self.form_layout = QFormLayout()
19  
20         # The salutations that we want to make available
21         self.salutations = ['Ahoy',
22                             'Good day',
23                             'Hello',
24                             'Heyo',
25                             'Hi',
26                             'Salutations',
27                             'Wassup',
28                             'Yo']
29  
30         # Create and fill the combo box to choose the salutation
31         self.salutation = QComboBox(self)
32         self.salutation.addItems(self.salutations)
33  
34         # Add it to the form layout with a label
35         self.form_layout.addRow('&Salutation:', self.salutation)
36  
37         # Create the entry control to specify a recipient
38         # and set its placeholder text
39         self.recipient = QLineEdit(self)
40         self.recipient.setPlaceholderText("e.g. 'world' or 'Matey'")
41  
42         # Add it to the form layout with a label
43         self.form_layout.addRow('&Recipient:', self.recipient)
44  
45         # Create and add the label to show the greeting text
46         self.greeting = QLabel('', self)
47         self.form_layout.addRow('Greeting:', self.greeting)
48  
49         # Add the form layout to the main VBox layout
50         self.layout.addLayout(self.form_layout)
51  
52         # Add stretch to separate the form layout from the button
53         self.layout.addStretch(1)
54  
55         # Create a horizontal box layout to hold the button
56         self.button_box = QHBoxLayout()
57  
58         # Add stretch to push the button to the far right
59         self.button_box.addStretch(1)
60  
61         # Create the build button with its caption
62         self.build_button = QPushButton('&Build Greeting', self)
63  
64         # Add it to the button box
65         self.button_box.addWidget(self.build_button)
66  
67         # Add the button box to the bottom of the main VBox layout
68         self.layout.addLayout(self.button_box)
69  
70         # Set the VBox layout as the window's main layout
71         self.setLayout(self.layout)
72  
73     def run(self):
74         # Show the form
75         self.show()
76         # Run the qt application
77         qt_app.exec_()
78  
79 # Create an instance of the application window and run it
80 app = LayoutExample()
81 app.run()

注意到这些对程序员来说是多么的容易。当代码不太短的时候——不是每个便捷都会使代码量减少,创建和嵌套布局有一定的代码开销的时候——精神上的负担就小多了。开发人员只需完成一个组合的布局,产生所需的效果,并创建他们;控件的创建和修改是隔离的,很少再要去考虑其影响到布局和其他控件。下一部分,我们将以这个例子创建的界面,让它实际上做些事。

 

By Ascii0x03

转载请注明出处:http://www.cnblogs.com/ascii0x03/p/5496699.html

 

    原文作者:ASCII0x03
    原文地址: https://www.cnblogs.com/ascii0x03/p/5496699.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞