我希望在我的简单 PyQT 应用程序上单击按钮时显示 MessageBox。我怎样才能声明两个文本框,并让 MessageBox 显示来自两个文本框的文本?
这是我的代码:
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_())
最佳答案
由于这种简单的代码是一种常见的要求,我决定一起破解一些基本的东西,给你:
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 编码实践——创建一个小部件作为窗口的中央小部件,用布局填充它,等等。
关于python - 如何在 PyQT4 上显示消息框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4155052/