|
PyQt4 Widget
組件(Widget)是一個應用最基本的構件。PyQt4 中有大量的組件。按鈕,選擇框,滑塊,列表等等。任何一個程序員都會需要這些組件。這篇中,我們將介紹一些有用的組件, QtGui.QCheckBox , ToggleButton , QtGui.QSlider , QtGui.QProcessBar 和 QtGui.QCalendarWidget 。
QtGui.QCheckBox
QtGui.QCheckBox 是一個組件有兩種狀態, On 和 Off 。它有一個標簽。選擇框通常代表那些可以開啟或關閉的特性,但是不會影響其他。
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 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: September 2011
"""
import sys
from PyQt4 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('QtGui.QCheckBox')
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.stateChanged.connect(self.changeTitle)
我們接著把 stateChanged 這個信號與自定義的 changeTitle() 方法連接起來。 changeTitle() 將用于開關窗口的標題。
ToggleButton
PyQt4 中沒有 ToggleButton 。為了創建 ToggleButton,我們使用 QtGui.QPushButton 的特殊模式。ToggleButton 是一個按鈕,有兩種狀態,按了與未按。你通過點擊進行開關。有很多情況下需要這樣的功能。
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 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: September 2011
"""
import sys
from PyQt4 import QtGui
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)
redb = QtGui.QPushButton('Green', self)
redb.setCheckable(True)
redb.move(10, 60)
redb.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()
在這里,我們創建了三個 ToggleButton 。我們還創建了一個 QtGui.QFrame 。我們先把它的顏色設為黑色。而 toggleButton 將會加入或取消相應的顏色組份。背景色取決于我們按了哪些按鈕。
self.col = QtGui.QColor(0, 0, 0)
這是顏色的初始值,黑色。
redb = QtGui.QPushButton('Red', self)
redb.setCheckable(True)
redb.move(10, 10)
為了創建 ToggleButton,我們創建了一個 QtGui.QPushButton ,并通過調用 setCheckable() 讓它可以被選中。
redb.clicked[bool].connect(self.setColor)
我們把點擊的信號和自定義的方法連接起來。
我們先獲取哪個按鈕被開關了。
if source.text() == "Red":
self.col.setRed(val)
如果是紅色按鈕,我們就相應地更改紅色的部分。
self.square.setStyleSheet("QFrame { background-color: %s }" %
self.col.name())
為了改變背景色,我們使用了樣式表。
QtGui.QSlider
QtGui.QSlider 是一個組件,只有一個滑塊。這個滑塊可以向前向后拖動。這就能讓我們選定一個值。有些時候,使用滑塊很自然,相對于簡單的提供一個數字或是一個旋鈕。 QtGui.QLable 可以顯示文字或圖片。
在我們的例子中,我們有一個滑塊和標簽。標簽將會顯示圖片,而滑塊用于控制標簽。
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
This example shows a QtGui.QSlider widget.
author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""
import sys
from PyQt4 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.QLable(self)
self.label.setPixmap(QtGui.QPixmap('mute.png'))
我們創建了一個 QtGui.QLabel 組件。我們設置一幅靜音的圖片在上面。
sld.valueChange[int].connect(self.changeValue)
我們把信號 valueChanged 和 changeValue() 方法聯系起來。
if value == 0:
self.label.setPixmap(QtGui.QPixmap('mute.png'))
...
基于滑塊的值,我們設置圖片到標簽上。前面的代碼,我們在滑塊的值為零時,設置靜音的圖片。
QtGui.QProgressBar
進度條常在處理很長的任務時使用。它是動態的,因此用戶可以知道我們的任務正在處理。在 PyQt4 中,進度條可以是水平或垂直。任務被分割成很多步。程序員可以設置進度條的最小值與最大值。默認值值 0,99 。
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
This example shows a QtGui.QProgressBar widget.
author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""
import sys
from PyQt4 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)
每個 QtCore.QObject 及其派生類都有 timerEvent() 這個句柄。為了對計時器事件做出回應,我們重新實現事件的句柄。
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.QCalendarWidget
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ZetCode PyQt4 tutorial
This example shows a QtGui.QCalendarWidget widget.
author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""
import sys
from PyQt4 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()
這個例子中有一個日歷和一個標簽。當前選中的日期會顯示在標簽中。
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() 方法獲取選中的日期。然后我們把日期對象轉為字符串并且設置到標簽中。
本部分,我們涉及了一些組件。
|