我是Qt Designer和PyCharm的新手,当我想制作一个小程序进行练习时,遇到了布局问题。
我使用Qt Designer设计布局,并使用PyUIC作为外部工具将我的login.ui转换为login.py。
我使用 Form 布局作为布局,并放置两对标签和lineEdits。
在运行程序之前,我先按预览按钮以检查布局,一切都按预期进行:
但是当我在PyCharm中运行程序时,它看起来很奇怪,我也不知道为什么:
我有两个.py文件:login.py和mainn.py
login.py:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(473, 436)
self.formLayout = QtWidgets.QFormLayout(Form)
self.formLayout.setObjectName("formLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole,
self.label)
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setObjectName("lineEdit")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole,
self.lineEdit)
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setObjectName("label_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole,
self.label_2)
self.lineEdit_2 = QtWidgets.QLineEdit(Form)
self.lineEdit_2.setObjectName("lineEdit_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole,
self.lineEdit_2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Label 1"))
self.label_2.setText(_translate("Form", "Label 2"))
mainn.py:
import sys
import login
from PyQt5.QtWidgets import QApplication, QMainWindow
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = login.Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
由于我正在运行高DPI 笔记本电脑,因此我不确定这是否是原因之一。有任何想法吗?谢谢!
答案 0 :(得分:0)
如果通过mainn.py
运行CMD
,则会看到错误消息:
QLayout: Attempting to add QLayout" "to QMainWindow" Form ", which already has a layout
尝试一下:
import sys
import login
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
# MainWindow = QMainWindow() # ---
MainWindow = QWidget() # +++
ui = login.Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())