215.md 2.0 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4
# Qt4 按钮

> 原文: [https://pythonspot.com/qt4-buttons/](https://pythonspot.com/qt4-buttons/)

W
wizardforcel 已提交
5 6 7
![PyQt4 button example](img/3911a344ee61b701979eb5a2de2c4e27.jpg)

PyQt4 button example
W
wizardforcel 已提交
8 9 10 11 12 13 14 15 16 17 18

PyQt4(Qt4)通过 QPushButton 小部件支持按钮。

我们扩展代码以在窗口中心显示一个按钮。

如果将鼠标悬停在该按钮上将显示一个工具提示,按下该按钮将关闭程序。

## PyQt4 按钮示例

The example below adds a button to a PyQt4 window.

W
wizardforcel 已提交
19
```py
W
wizardforcel 已提交
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Set window size.
w.resize(320, 240)

# Set window title
w.setWindowTitle("Hello World!")

# Add a button
btn = QPushButton('Hello World!', w)
btn.setToolTip('Click to quit!')
btn.clicked.connect(exit)
btn.resize(btn.sizeHint())
btn.move(100, 80)

# Show window
w.show()

sys.exit(a.exec_())

```

## PyQt4 信号和插槽

A button click should do something. To do so, you must use signals and slots.

如果用户执行诸如单击按钮,在框中键入文本之类的操作,则小部件会发出信号。 信号可以与一个插槽相连,该插槽充当接收器并对其起作用。

W
wizardforcel 已提交
58
```py
W
wizardforcel 已提交
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
import sys
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *

# create our window
app = QApplication(sys.argv)
w = QWidget()
w.setWindowTitle('Button click example @pythonspot.com')

# Create a button in the window
btn = QPushButton('Click me', w)

# Create the actions
@pyqtSlot()
def on_click():
    print('clicked')

@pyqtSlot()
def on_press():
    print('pressed')

@pyqtSlot()
def on_release():
    print('released')

# connect the signals to the slots
btn.clicked.connect(on_click)
btn.pressed.connect(on_press)
btn.released.connect(on_release)

# Show the window and run the app
w.show()
app.exec_()

```

[下载 PyQT 代码(批量收集)](https://pythonspot.com/python-qt-examples/)