如何在PyQT4中显示消息框?
我想在我的简单PyQT应用程序中,当我点击一个按钮时显示一个消息框。请问我该如何声明两个文本框,并让消息框显示这两个文本框中的文本呢?
这是我目前的代码:
import sys
from PyQt4 import QtGui, QtCore
class myWindow(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
#The setGeometry method is used to position the control.
#Order: X, Y position - Width, Height of control.
self.setGeometry(300, 300, 500, 350)
self.setWindowTitle("Sergio's QT Application.")
self.setWindowIcon(QtGui.QIcon('menuScreenFolderShadow.png'))
self.setToolTip('<i>Welcome</i> to the <b>first</b> app ever!')
QtGui.QToolTip.setFont(QtGui.QFont('Helvetica', 12))
txtFirstName = QtGui.?
txtLastName = QtGui.?
btnQuit = QtGui.QPushButton('Exit Application', self)
btnQuit.setGeometry(340, 300, 150, 35)
self.connect(btnQuit, QtCore.SIGNAL('clicked()'),
QtGui.qApp, QtCore.SLOT('quit()'))
app = QtGui.QApplication(sys.argv)
mainForm = myWindow()
mainForm.show()
sys.exit(app.exec_())
3 个回答
3
from PyQt4 import QtGui, QtCore
class Window( QtGui.QWidget ):
def __init__( self ):
QtGui.QWidget.__init__( self )
msgBox = QtGui.QMessageBox( self )
msgBox.setIcon( QtGui.QMessageBox.Information )
msgBox.setText( "Do not stare into laser with remaining eye" )
msgBox.setInformativeText( "Do you really want to disable safety enforcement?" )
msgBox.addButton( QtGui.QMessageBox.Yes )
msgBox.addButton( QtGui.QMessageBox.No )
msgBox.setDefaultButton( QtGui.QMessageBox.No )
ret = msgBox.exec_()
if ret == QtGui.QMessageBox.Yes:
print( "Yes" )
return
else:
print( "No" )
return
if __name__ == '__main__':
import sys
app = QtGui.QApplication( sys.argv )
window = Window()
# window.show()
sys.exit( app.exec_() )
来源:
4
安装PyQt的时候,它会自带一些示例。这些示例里面有很多非常有用的代码,你可以从中学习,也可以直接拿一些代码块来用。
比如,你可以看看“地址簿”这个示例,它会弹出消息框,还有其他功能(你可以在它的源代码里搜索“messagebox”来找到相关内容)。
23
因为这种简单的代码是大家常常需要的,我决定简单拼凑一下,给你们看看:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AppForm(QMainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.create_main_frame()
def create_main_frame(self):
page = QWidget()
self.button = QPushButton('joy', page)
self.edit1 = QLineEdit()
self.edit2 = QLineEdit()
vbox1 = QVBoxLayout()
vbox1.addWidget(self.edit1)
vbox1.addWidget(self.edit2)
vbox1.addWidget(self.button)
page.setLayout(vbox1)
self.setCentralWidget(page)
self.connect(self.button, SIGNAL("clicked()"), self.clicked)
def clicked(self):
QMessageBox.about(self, "My message box", "Text1 = %s, Text2 = %s" % (
self.edit1.text(), self.edit2.text()))
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
form = AppForm()
form.show()
app.exec_()
在文本框里输入一些东西,然后点击按钮。就可以了!:-)
注意:其实可以用更少的代码来实现,但这样做是一个很好的PyQt编程练习——创建一个小部件作为窗口的中心部件,给它添加布局等等。