定制化对话框
当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)
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“参数,否则,对话框是不会弹出来的。