主要內容
- 通過繼承實現自己的界面類;
- 涉及模塊:QDialog, QLineEdit , QTextBrowser
- 界面布局:絕對布局,布局類
實例講解
先看一段代碼,我們定義了一個類Form,它繼承自QDialog
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) self.browser = QTextBrowser() self.lineedit = QLineEdit("Type an expression and press Enter") self.lineedit.selectAll() layout = QVBoxLayout() #垂直盒式布局 layout.addWidget(self.browser) layout.addWidget(self.lineedit)<br> #layout = QGridLayout() #網格布局 #layout.addWidget(self.browser,0, 0) #layout.addWidget(self.lineedit,0, 0) self.setLayout(layout) self.lineedit.setFocus() self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi) #信號綁定到槽 self.setWindowTitle("Calculate") def updateUi(self): try: text = unicode(self.lineedit.text()) self.browser.append("%s = <b>%s</b>" % (text, eval(text))) except: self.browser.append( "<font color=red>%s is invalid!</font>" % text) app = QApplication(sys.argv) form = Form() form.show() app.exec_()
(1) QDialog是窗口類, QLineEdit文本框,QTextBrowser顯示內容的文本區域,支持html格式語法。
(2)layout = QVBoxLayout() 垂直盒式布局,即內容對象上下排列
說到布局,主要分為兩類:絕對布局,相對布局(相應類)
- 絕對布局,調用move(x,y)方法
- 相對布局,常用的有 QHBoxLayout, QVBoxLayout 和QGridLayout (網格布局)
(3)特別注意的是 self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
這是PyQt的事件處理機制 ---- 信號與槽(Signals and slots):
信號相當於一個事件:如點擊按鈕,完成輸入后按回車等等;槽相當於處理函數。
在上面程序中,當在文本框中完成輸入按回車時,就會調用updateUi函數,這就是connect綁定的效果。
程序效果如下:
簡要總結:
- 通過繼承實現窗體類
- 窗口布局方法
- QDialog, QLineEdit , QTextBrowser
- QLineEdit 方法:
- 獲取unicode 文本: unicode(lineEdit.text())
- QTextBrowser 方法:
- 添加內容 textBrowser.appen("formatText")
- 信號與槽
- self.connect(widget, signal , slot)
擴展知識:
熟悉常用的窗口組件:
1 按鈕類
QPushButton |
普通按鈕 |
QToolButton |
工具按鈕:通常在工具欄使用 |
QRadioButton |
單選框 |
QCheckBox |
復選框 |
QCommanLinkButton |
Vista風格的命令鏈接按鈕 |
QDialogButtonBox |
對話框按鈕組:確定、取消 |
2 顯示組件
QLabel |
標簽 |
QTextBrowser |
文本區域 |
QGraphicsView |
圖像顯示 |
QCalendarWidget |
日歷組件 |
QProgressBar |
進度條 |
QLCDNumber |
液晶數字顯示 |
QWebView |
Web瀏覽器視圖 |
QDeclarativeView |
顯示Qt聲明的用戶接口 |
3 輸入組件
QComboBox |
下拉選框 |
QFontComboBox |
字體選擇 |
QLineEdit |
單行文本框 |
QTextEdit |
多行文本框(富文本) |
QPlainTextEdit |
多行文本框(純文本) |
QSpinBox |
整數范圍調節器 |
QDoubleSpinBox |
實型范圍調節器 |
QDial |
環形范圍調節器 |
QSlider |
滑動調節器 |
QTimeEdit |
時間輸入框 |
QDateEdit |
日期輸入框 |
QDateTimeEdit |
時間日期輸入框 |
4 容器類
QFrame |
幀窗口 |
QWidget |
界面部件,所有界面對象類的基類 |
QToolBox |
工具欄容器 |
QTabWidget |
多標簽容器 |
QStackedWidget |
層次容器,一次只有一個可見 |
QScollArea |
滾動區域 |
QGroupBox |
對象組容器 |
QMdiArea |
多文檔容器 |
QDockWidget |
懸浮容器 |
QDail, QSpinBox的使用
QDial:環形的范圍選擇器
QSpinBox :下拉列表形式的整數選擇器
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) dial = QDial() dial.setNotchesVisible(True) spinbox = QSpinBox() layout = QHBoxLayout() layout.addWidget(dial) layout.addWidget(spinbox) self.setLayout(layout) self.connect(dial, SIGNAL("valueChanged(int)"),spinbox.setValue) self.connect(spinbox, SIGNAL("valueChanged(int)"),dial.setValue) self.setWindowTitle("Signals and Slots")