215.md 2.1 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 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
# Qt4 按钮

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

![PyQt4 button example](img/3911a344ee61b701979eb5a2de2c4e27.jpg) PyQt4 button example

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

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

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

**相关课程:**

*   [使用 PyQt5 创建 GUI 应用](https://gum.co/pysqtsamples)

## PyQt4 按钮示例

The example below adds a button to a PyQt4 window.

```
#! /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.

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

```
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/)