PyQt5教程(五)——對話框

原文:http://zetcode.com/gui/pyqt5/dialogs/python

對話框或對話窗口是現代GUI程序不可或缺的一部分。對話的定義是兩個或多我的之間的交談。在計算機程序中對話是與程序進行「交談」的窗體。對話框用於輸入數據、修改數據、更改程序設置等。web

QInputDialog

QInputDialog提供了從用戶取得一個輸入的簡便對話框。輸入的值能夠是字符串、數字或列表中的一項。app

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we receive data from
a QInputDialog dialog. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, 
    QInputDialog, QApplication)


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        self.btn = QPushButton('Dialog', self)
        self.btn.move(20, 20)
        self.btn.clicked.connect(self.showDialog)
        
        self.le = QLineEdit(self)
        self.le.move(130, 22)
        
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Input dialog')
        self.show()
        
        
    def showDialog(self):
        
        text, ok = QInputDialog.getText(self, 'Input Dialog', 
            'Enter your name:')
        
        if ok:
            self.le.setText(str(text))
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

這個例子中有一個按鈕和一個LineEdit控件。按鈕用於顯示對話框以取得用戶輸入。輸入的文本會顯示在LineEdit控件中。學習

text, ok = QInputDialog.getText(self, 'Input Dialog', 
    'Enter your name:')

這行代碼用於顯示QInputDialog對話框。第一個字符串參數是對話框的標題,第二個是對話框中的消息。QInputDialog.getText方法會返回用戶輸入的文本和一個布爾值。當點擊OK按鈕時,這個布爾值爲true。字體

if ok:
    self.le.setText(str(text))

從對話框中取得的文本會顯示在LineEdit控件上。ui

Input Dialog

QColorDialog

QColorDialog提供了一個用於選擇顏色值的對話框。this

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we select a color value
from the QColorDialog and change the background
color of a QFrame widget. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QFrame, 
    QColorDialog, QApplication)
from PyQt5.QtGui import QColor


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        col = QColor(0, 0, 0) 

        self.btn = QPushButton('Dialog', self)
        self.btn.move(20, 20)

        self.btn.clicked.connect(self.showDialog)

        self.frm = QFrame(self)
        self.frm.setStyleSheet("QWidget { background-color: %s }" 
            % col.name())
        self.frm.setGeometry(130, 22, 100, 100)            
        
        self.setGeometry(300, 300, 250, 180)
        self.setWindowTitle('Color dialog')
        self.show()
        
        
    def showDialog(self):
      
        col = QColorDialog.getColor()

        if col.isValid():
            self.frm.setStyleSheet("QWidget { background-color: %s }"
                % col.name())
            
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

示例展現了一個按鈕和一個QFrame。QFrame控件的背景設置爲黑色。使用QColorDialog咱們能夠改變它的背景色。code

col = QColor(0, 0, 0)

這是QtGui.QFrame的初始背景顏色。blog

col = QColorDialog.getColor()

這行代碼會彈出QColorDialog對話框。繼承

if col.isValid():
    self.frm.setStyleSheet("QWidget { background-color: %s }"
        % col.name())

咱們要先檢查col的值。若是點擊的是Cancel按鈕,返回的顏色值是無效的。當顏色值有效時,咱們經過樣式表(style sheet)來改變背景顏色。

QFontDialog

QFontDialog是一個用於選擇字體的對話框控件。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we select a font name
and change the font of a label. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QPushButton, 
    QSizePolicy, QLabel, QFontDialog, QApplication)


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        vbox = QVBoxLayout()

        btn = QPushButton('Dialog', self)
        btn.setSizePolicy(QSizePolicy.Fixed,
            QSizePolicy.Fixed)
        
        btn.move(20, 20)

        vbox.addWidget(btn)

        btn.clicked.connect(self.showDialog)
        
        self.lbl = QLabel('Knowledge only matters', self)
        self.lbl.move(130, 20)

        vbox.addWidget(self.lbl)
        self.setLayout(vbox)          
        
        self.setGeometry(300, 300, 250, 180)
        self.setWindowTitle('Font dialog')
        self.show()
        
        
    def showDialog(self):

        font, ok = QFontDialog.getFont()
        if ok:
            self.lbl.setFont(font)
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

在這個例子中,咱們建立了一個按鈕和一個標籤(Label),並經過QFontDialog來改變標籤的字體。

font, ok = QFontDialog.getFont()

這段代碼會彈出字體選擇對話框。getFont()方法會返回選定的字體名稱和一個ok參數。當點擊了OK按鈕時ok的值爲True,不然爲False。

if ok:
    self.label.setFont(font)

點擊OK按鈕會改變標籤中的字體。

FontDialog

QFileDialog

QFileDialog是一個讓用戶選擇文件或目錄的對話框。可用於選擇打開或保存文件。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we select a file with a
QFileDialog and display its contents
in a QTextEdit.

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QMainWindow, QTextEdit, 
    QAction, QFileDialog, QApplication)
from PyQt5.QtGui import QIcon


class Example(QMainWindow):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):      

        self.textEdit = QTextEdit()
        self.setCentralWidget(self.textEdit)
        self.statusBar()

        openFile = QAction(QIcon('open.png'), 'Open', self)
        openFile.setShortcut('Ctrl+O')
        openFile.setStatusTip('Open new File')
        openFile.triggered.connect(self.showDialog)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openFile)       
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('File dialog')
        self.show()
        
        
    def showDialog(self):

        fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')

        if fname[0]:
            f = open(fname[0], 'r')

            with f:
                data = f.read()
                self.textEdit.setText(data)        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

這個例子展現了一個菜單欄,中部TextEdit控件和一個狀態欄。菜單項Open會顯示用於選擇文件的QtGui.QFileDialog對話框。選定文件的內容會加載到TextEdit控件中。

class Example(QMainWindow):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()

示例窗體繼承自QMainWindow,由於咱們要將TextEdit控件置於窗體中央。

fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')

這時會彈出QFileDialog對話框。第一個字符串參數是對話框的標題。第二個指定對話框的工做目錄。默認狀況下文件篩選器會匹配全部類型的文件(*)

if fname[0]:
    f = open(fname[0], 'r')

    with f:
        data = f.read()
        self.textEdit.setText(data)

讀取了選擇的文件名稱並將文件內容加載到了TextEdit控件。

File dialog

在這部分教程中咱們學習了對話框。

相關文章
相關標籤/搜索