160.md 13.4 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# PySide 小部件

> 原文: [http://zetcode.com/gui/pysidetutorial/widgets/](http://zetcode.com/gui/pysidetutorial/widgets/)

W
wizardforcel 已提交
5
小部件是应用的基本构建块。 PySide 编程工具包包含各种小部件。 按钮,复选框,滑块,列表框等。程序员完成工作所需的一切。 在本教程的这一部分中,我们将描述几个有用的小部件。 即`QtGui.QCheckBox``ToggleButton``QtGui.QSlider``QtGui.QProgressBar``QtGui.QCalendarWidget`
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
## `QtGui.QCheckBox`
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
`QtGui.QCheckBox`是具有两种状态的窗口小部件:打开和关闭。 这是一个带有标签的盒子。 复选框通常用于表示应用中可以启用或禁用而不会影响其他功能的功能。
W
wizardforcel 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

```
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

In this example, a QtGui.QCheckBox widget
is used to toggle the title of a window.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        cb = QtGui.QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QtGui.QCheckBox')
        self.show()

    def changeTitle(self, state):

        if state == QtCore.Qt.Checked:
            self.setWindowTitle('Checkbox')
        else:
            self.setWindowTitle('')

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

```

在我们的示例中,我们将创建一个复选框,以切换窗口标题。

```
cb = QtGui.QCheckBox('Show title', self)

```

这是`QtGui.QCheckBox`构造函数。

```
cb.toggle()

```

我们设置了窗口标题,因此我们还必须选中该复选框。

```
cb.stateChanged.connect(self.changeTitle)

```

我们将用户定义的`changeTitle()`方法连接到`stateChanged`信号。 `changeTitle()`方法将切换窗口标题。

```
def changeTitle(self, state):

    if state == QtCore.Qt.Checked:
        self.setWindowTitle('Checkbox')
    else:
        self.setWindowTitle('')

```

我们在状态变量中接收复选框的状态。 如果已设置,则设置窗口的标题。 否则,我们使用一个空字符串作为标题。

![QtGui.QCheckBox](img/65f2930dcdd6beb1f4a8dd2b67ea11fd.jpg)

Figure: QtGui.QCheckBox

W
wizardforcel 已提交
104
## 开关按钮
W
wizardforcel 已提交
105

W
wizardforcel 已提交
106
PySide 没有用于开关按钮的小部件。 要创建开关按钮,我们在特殊模式下使用`QtGui.QPushButton`。 开关按钮是具有两种状态的按钮。 已按下但未按下。 通过单击可以在这两种状态之间切换。 在某些情况下此功能非常合适。
W
wizardforcel 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

```
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

In this example, we create three toggle buttons.
They will control the background color of a 
QtGui.QFrame. 

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        self.col = QtGui.QColor(0, 0, 0)       

        redb = QtGui.QPushButton('Red', self)
        redb.setCheckable(True)
        redb.move(10, 10)

        redb.clicked[bool].connect(self.setColor)

        greenb = QtGui.QPushButton('Green', self)
        greenb.setCheckable(True)
        greenb.move(10, 60)

        greenb.clicked[bool].connect(self.setColor)

        blueb = QtGui.QPushButton('Blue', self)
        blueb.setCheckable(True)
        blueb.move(10, 110)

        blueb.clicked[bool].connect(self.setColor)

        self.square = QtGui.QFrame(self)
        self.square.setGeometry(150, 20, 100, 100)
        self.square.setStyleSheet("QWidget { background-color: %s }" %  
            self.col.name())

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Toggle button')
        self.show()

    def setColor(self, pressed):

        source = self.sender()

        if pressed:
            val = 255
        else: val = 0

        if source.text() == "Red":
            self.col.setRed(val)                
        elif source.text() == "Green":
            self.col.setGreen(val)             
        else:
            self.col.setBlue(val) 

        self.square.setStyleSheet("QFrame { background-color: %s }" %
            self.col.name())  

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

```

在我们的示例中,我们创建了三个 ToggleButtons。 我们还创建了一个`QtGui.QFrame`小部件。 我们将小部件的背景色设置为黑色。 切换按钮将切换颜色值的红色,绿色和蓝色部分。 背景颜色取决于我们按下的切换按钮。

```
self.col = QtGui.QColor(0, 0, 0)  

```

这是初始颜色值。 它是黑色的。

```
greenb = QtGui.QPushButton('Green', self)
greenb.setCheckable(True)

```

W
wizardforcel 已提交
209
要创建开关按钮,我们创建一个`QtGui.QPushButton`并通过调用`setCheckable()`方法使其可检查。
W
wizardforcel 已提交
210 211 212 213 214 215

```
greenb.clicked[bool].connect(self.setColor)

```

W
wizardforcel 已提交
216
我们将`clicked[bool]`信号连接到用户定义的方法。 请注意,此信号类型将`bool`参数发送给该方法。 参数值是 true 还是 false,取决于按钮的状态,例如 是否检查/切换。
W
wizardforcel 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

```
source = self.sender()

```

我们得到信号的发送者。 这是被切换的按钮。

```
if source.text() == "Red":
    self.col.setRed(val)   

```

如果它是红色按钮,我们将相应地更新颜色的红色部分。

```
self.square.setStyleSheet("QFrame { background-color: %s }" %
    self.col.name())    

```

我们使用样式表来更改`QtGui.QFrame`小部件的背景颜色。

![ToggleButton](img/da8ddc61d9d8b35d1f78791abe7ac1f2.jpg)

Figure: ToggleButton

W
wizardforcel 已提交
245
## `QtGui.QSlider`
W
wizardforcel 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

`QtGui.QSlider`是具有简单句柄的小部件。 该手柄可以前后拉动。 这样,我们可以为特定任务选择一个值。 有时使用滑块比只提供一个数字或使用旋转框更为自然。 `QtGui.QLabel`显示文本或图像。

在我们的示例中,我们将显示一个滑块和一个标签。 这次,标签将显示图像。 滑块将控制标签。

```
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QSlider widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)
        sld.setFocusPolicy(QtCore.Qt.NoFocus)
        sld.setGeometry(30, 40, 100, 30)
        sld.valueChanged[int].connect(self.changeValue)

        self.label = QtGui.QLabel(self)
        self.label.setPixmap(QtGui.QPixmap('mute.png'))
        self.label.setGeometry(160, 40, 80, 30)

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QtGui.QSlider')
        self.show()

    def changeValue(self, value):

        if value == 0:
            self.label.setPixmap(QtGui.QPixmap('mute.png'))
        elif value > 0 and value <= 30:
            self.label.setPixmap(QtGui.QPixmap('min.png'))
        elif value > 30 and value < 80:
            self.label.setPixmap(QtGui.QPixmap('med.png'))
        else:
            self.label.setPixmap(QtGui.QPixmap('max.png'))

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

```

在我们的示例中,我们模拟了音量控制。 通过拖动滑块的手柄,我们可以更改标签上的图像。

```
sld = QtGui.QSlider(QtCore.Qt.Horizontal, self)

```

在这里,我们创建一个水平`QtGui.QSlider`

```
self.label = QtGui.QLabel(self)
self.label.setPixmap(QtGui.QPixmap('mute.png'))

```

我们创建一个`QtGui.QLabel`小部件。 并为其设置初始静音图像。

```
sld.valueChanged[int].connect(self.changeValue)

```

W
wizardforcel 已提交
334
我们将`valueChanged[int]`信号连接到用户定义的`changeValue()`方法。
W
wizardforcel 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348

```
if value == 0:
    self.label.setPixmap(QtGui.QPixmap('mute.png'))
...

```

基于滑块的值,我们将图像设置为标签。 在上面的代码中,如果滑块值等于零,则将`mute.png`图像设置为标签。

![QtGui.QSlider widget](img/4803c978348d6b886bb4da71f2631dff.jpg)

Figure: QtGui.QSlider widget

W
wizardforcel 已提交
349
## `QtGui.QProgressBar`
W
wizardforcel 已提交
350

W
wizardforcel 已提交
351
进度条是当我们处理冗长的任务时使用的小部件。 它具有动画效果,以便用户知道我们的任务正在进行中。 `QtGui.QProgressBar`小部件在 PySide 工具箱中提供了水平或垂直进度条。 程序员可以为进度条设置最小值和最大值。 默认值为 0,99。
W
wizardforcel 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

```
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QProgressBar widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        self.pbar = QtGui.QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)

        self.btn = QtGui.QPushButton('Start', self)
        self.btn.move(40, 80)
        self.btn.clicked.connect(self.doAction)

        self.timer = QtCore.QBasicTimer()
        self.step = 0

        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('QtGui.QProgressBar')
        self.show()

    def timerEvent(self, e):

        if self.step >= 100:
            self.timer.stop()
            self.btn.setText('Finished')
            return
        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def doAction(self):

        if self.timer.isActive():
            self.timer.stop()
            self.btn.setText('Start')
        else:
            self.timer.start(100, self)
            self.btn.setText('Stop')

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

```

在我们的示例中,我们有一个水平进度条和一个按钮。 该按钮将启动和停止进度条。

```
self.pbar = QtGui.QProgressBar(self)

```

这是一个`QtGui.QProgressBar`构造函数。

```
self.timer = QtCore.QBasicTimer()

```

要激活进度条,我们使用计时器对象。

```
self.timer.start(100, self)

```

要启动计时器事件,我们调用`start()`方法。 此方法有两个参数。 超时和将接收事件的对象。

```
def timerEvent(self, e):

    if self.step >= 100:
        self.timer.stop()
        self.btn.setText('Finished')
        return
    self.step = self.step + 1
    self.pbar.setValue(self.step)

```

W
wizardforcel 已提交
457
每个`QtCore.QObject`及其子代都有一个`timerEvent()`事件处理程序。 为了对计时器事件做出反应,我们重新实现了事件处理程序。 我们更新`self.step`变量,并为进度栏小部件设置一个新值。
W
wizardforcel 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

```
def doAction(self):

    if self.timer.isActive():
        self.timer.stop()
        self.btn.setText('Start')
    else:
        self.timer.start(100, self)
        self.btn.setText('Stop')

```

`doAction()`方法中,我们启动和停止计时器。

![QtGui.QProgressBar](img/b4ee2275960055c64c291c3e29c819c7.jpg)

Figure: QtGui.QProgressBar

W
wizardforcel 已提交
477
## `QtGui.QCalendarWidget`
W
wizardforcel 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

`QtGui.QCalendarWidget`提供基于月度的日历小部件。 它允许用户以简单直观的方式选择日期。

```
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a QtGui.QCalendarWidget widget.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):      

        cal = QtGui.QCalendarWidget(self)
        cal.setGridVisible(True)
        cal.move(20, 20)
        cal.clicked[QtCore.QDate].connect(self.showDate)

        self.lbl = QtGui.QLabel(self)
        date = cal.selectedDate()
        self.lbl.setText(date.toString())
        self.lbl.move(130, 260)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Calendar')
        self.show()

    def showDate(self, date):     
        self.lbl.setText(date.toString())

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

```

该示例具有日历小部件和标签小部件。 当前选择的日期显示在标签窗口小部件中。

```
self.cal = QtGui.QCalendarWidget(self)

```

我们构造一个日历小部件。

```
cal.clicked[QtCore.QDate].connect(self.showDate)

```

如果我们从小部件中选择一个日期,则会发出`clicked[QtCore.QDate]`信号。 我们将此信号连接到用户定义的`showDate()`方法。

```
def showDate(self, date):     
    self.lbl.setText(date.toString())

```

我们调用`selectedDate()`方法检索所选日期。 然后,我们将日期对象转换为字符串并将其设置为标签小部件。

![QtGui.QCalendarWidget widget](img/2873ff9595bbe5c4bc74dd75e71ea097.jpg)

Figure: QtGui.QCalendarWidget widget

在 PySide 教程的这一部分中,我们介绍了几个小部件。