PyQt5 對話框


Qt對話框有普通消息框,還有文字,顏色,字體等多種對話框類控件。直接上代碼好了。

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class SDialog(QWidget):
    def __init__(self, parent = None):
        super(SDialog, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setWindowTitle("Dialog")
        self.setGeometry(300,300,450,250)
        #設定窗口標題和窗口的大小和位置。

        inputButton = QPushButton(self.tr("用戶輸入對話框"))
        fileButton = QPushButton(self.tr("文件選擇對話框"))
        colorButton = QPushButton(self.tr("顏色選擇對話框"))
        fontButton = QPushButton(self.tr("字體選擇對話框"))

        self.inputL = QLineEdit()
        self.filelL = QLineEdit()
        # 創建兩個QlineEdit實例,來顯示選擇的內容
        self.colorFrame = QFrame()
        self.colorFrame.setFrameShape(QFrame.Box)
        self.colorFrame.setAutoFillBackground(True)
        # 創建一個Frame實例用來顯示顏色
        self.fontL = QLabel("Hello World!")

        grid = QGridLayout()
        grid.addWidget(inputButton, 1, 0)
        grid.addWidget(self.inputL, 1, 1)
        grid.addWidget(fileButton, 2, 0)
        grid.addWidget(self.filelL, 2, 1)
        grid.addWidget(colorButton, 3, 0)
        grid.addWidget(self.colorFrame, 3, 1)
        grid.addWidget(fontButton, 4, 0)
        grid.addWidget(self.fontL, 4, 1)
        self.setLayout(grid)
        #網格類布局

        inputButton.clicked.connect(self.openInput)
        fileButton.clicked.connect(self.openFile)
        colorButton.clicked.connect(self.openColor)
        fontButton.clicked.connect(self.openFont)
        #把四個按鈕控件的clicked()信號和槽連接

    def openInput(self):
        t, ok = QInputDialog.getText(self, "用戶輸入對話框",  "請輸入任意內容" )
        if ok:
            self.inputL.setText(t)

    def openFile(self):
        s = QFileDialog.getOpenFileName(self, "open file dialog", "d:/", "python file(*py)")
        self.filelL.setText(s[0])

    def openColor(self):
        c = QColorDialog.getColor(Qt.blue)
        if c.isValid():
            self.colorFrame.setPalette(QPalette(c))

    def openFont(self):
        f, ok = QFontDialog.getFont()
        if ok:
            self.fontL.setFont(f)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    form = SDialog()
    form.show()
    app.exec_()

QInputDialog除了可以選擇讓用戶輸入文字還有可以輸入int和雙精度浮點數等等。參數2和3分別為窗口標題和提示內容。

QFileDialog.getOpenFileName()第二個參數為窗口標題,第三個為選擇打開文件的目錄,第四個是篩選打開文件的類型

QColorDialog.getColor()如果有返回值,那么c.isValid就會有值,執行設置frame的顏色。

QfontDialog.getFont()返回一個Qfont對象和一個布爾值組成的元組。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM