今天初次使用了PyQt5,感觉不错。
注意的问题是,PyQt5貌似只支持Python 3
碰到的问题:
没有找到QString类型,貌似是使用的Python的内建str类型。因此无法使用trimmed等方法,而要使用strip()方法。
connect方法和C++版本不一样。具体情况见代码。
在Qt5中,没有找到QVBoxLayout的setMargin方法,查找文档发现已经替换成了setContentsMargins方法。
OK,看一下代码吧:
#!/usr/bin/python3#coding:utf-8from PyQt5.QtWidgets import *import sysclass LoginDlg(QDialog): def __init__(self, parent=None): super(LoginDlg, self).__init__(parent) usr = QLabel("用户:") pwd = QLabel("密码:") self.usrLineEdit = QLineEdit() self.pwdLineEdit = QLineEdit() self.pwdLineEdit.setEchoMode(QLineEdit.Password) gridLayout = QGridLayout() gridLayout.addWidget(usr, 0, 0, 1, 1) gridLayout.addWidget(pwd, 1, 0, 1, 1) gridLayout.addWidget(self.usrLineEdit, 0, 1, 1, 3); gridLayout.addWidget(self.pwdLineEdit, 1, 1, 1, 3); okBtn = QPushButton("确定") cancelBtn = QPushButton("取消") btnLayout = QHBoxLayout() btnLayout.setSpacing(60) btnLayout.addWidget(okBtn) btnLayout.addWidget(cancelBtn) dlgLayout = QVBoxLayout() dlgLayout.setContentsMargins(40, 40, 40, 40) dlgLayout.addLayout(gridLayout) dlgLayout.addStretch(40) dlgLayout.addLayout(btnLayout) self.setLayout(dlgLayout) okBtn.clicked.connect(self.accept) cancelBtn.clicked.connect(self.reject) self.setWindowTitle("登录") self.resize(300, 200) def accept(self): if self.usrLineEdit.text().strip() == "eric" and self.pwdLineEdit.text() == "eric": super(LoginDlg, self).accept() else: QMessageBox.warning(self, "警告", "用户名或密码错误!", QMessageBox.Yes) self.usrLineEdit.setFocus()app = QApplication(sys.argv)dlg = LoginDlg()dlg.show()dlg.exec_()app.exit()
效果如下:
联系客服