Python Qt定义自己的对话框

定制化对话框

     当QMessageBox不能满足你的需要时,例如你需要在对话框中加入QLabel、QTextBrowser等显示控件时。此时需要继承QDialog,然后实现自己所需要的功能。
本例中在弹出的对话框中,加入QLabel、QTextBrowser和两个按钮。代码如下:
import sys
from PyQt4 import QtCore, QtGui
class SaveDialog(QtGui.QDialog):#继承QDialog类
    def __init__(self, parent=None):
        super(SaveDialog, self).__init__(parent)
        label = QtGui.QLabel("Title")
        lineEdit = QtGui.QTextBrowser()
        label.setBuddy(lineEdit)

        cacelButton = QtGui.QPushButton("Cacel")
        saveButton = QtGui.QPushButton("Save")
        saveButton.clicked.connect(self.close)#当点击save按钮时,对话框将会消失,点击Cacel按钮时,则不会消失。
        buttonBox = QtGui.QDialogButtonBox(QtCore.Qt.Horizontal)
        
        buttonBox.addButton(saveButton, QtGui.QDialogButtonBox.RejectRole)
        buttonBox.addButton(cacelButton, QtGui.QDialogButtonBox.YesRole)        

        topLeftLayout = QtGui.QVBoxLayout()
        topLeftLayout.addWidget(label)
        topLeftLayout.addWidget(lineEdit)

        leftLayout = QtGui.QHBoxLayout()
        leftLayout.addLayout(topLeftLayout)
        leftLayout.addStretch(1)

        mainLayout = QtGui.QGridLayout()
        mainLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
        mainLayout.addLayout(leftLayout, 0, 0)
        mainLayout.addWidget(buttonBox, 1, 0)
        self.setLayout(mainLayout)
        self.setWindowTitle("Save or Not")

class Ui(QtGui.QWidget): #主UI
    def __init__(self):
        super(Ui,self).__init__()
self.show_button=QtGui.QPushButton("Show Dialog")
H_layout=QtGui.QHBoxLayout()
H_layout.addWidget(self.show_button)
self.setLayout(H_layout)
self.show_button.clicked.connect(self.show_dialog)
    def show_dialog(self) :
dialog=SaveDialog( self)
dialog.show()
def main():
    app = QtGui.QApplication(sys.argv)
    ui = Ui()
    ui.show()
    sys.exit(app.exec_())
    pass
if __name__ == '__main__':
    main()
    pass
运行上面的程序,点击主界面中的按钮,就会弹出你定制的弹框。

在主界面中调佣弹框时,dialog=SaveDialog( self),需要加入”self“参数,否则,对话框是不会弹出来的。
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值