Qt4 按鈕
Qt4 按鈕
PyQt4(Qt4)
通過 QPushButton 控制元件支援按鈕。
我們擴充套件程式碼以在視窗中心顯示一個按鈕。
如果懸停,按鈕將顯示工具提示,按下時將關閉程式。
PyQt4 按鈕示例
下面的示例為 PyQt4 視窗新增了一個按鈕。
#! /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 訊號和槽
點選按鈕應該做一些事情。為此,你必須使用訊號和槽。
如果使用者執行諸如單擊按鈕,在框中鍵入文字等操作,則視窗控制元件會發出訊號。訊號可以與插槽連線,插槽充當接收器並作用於其上。
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_()