PyQt5如何在不使用布局的QWidget新窗口中正常展示各类控件
问题原因
你创建的QLabel、QLineEdit、QPushButton等控件均未绑定父容器,PyQt中无父对象的控件会作为独立窗口存在,不会自动渲染到当前PasswordForm窗口内部。
解决方案
方案1:适配现有绝对定位写法
在每个控件初始化时传入self作为父参数即可,修改后的PasswordForm代码如下:
class PasswordForm(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Password") self.setFixedWidth(400) self.setFixedHeight(300) # 所有控件传入self作为父对象 self.label = QLabel("Enter Admin Password:", self) self.label.setGeometry(QtCore.QRect(80, 20, 211, 31)) self.label.setMinimumSize(QtCore.QSize(0, 31)) self.label.setObjectName("label") self.admin_pass_input = QLineEdit(self) self.admin_pass_input.setGeometry(QtCore.QRect(80, 50, 161, 25)) self.admin_pass_input.setEchoMode(QtWidgets.QLineEdit.Password) self.admin_pass_input.setObjectName("admin_pass_input") self.pushButton = QPushButton("OK", self) self.pushButton.setGeometry(QtCore.QRect(120, 80, 89, 25))
修改后重新运行即可看到窗口内的所有控件。
方案2:使用布局管理器(更易维护)
硬编码坐标的绝对定位适配性差,推荐用PyQt内置布局管理器自动排布控件,代码如下:
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout class PasswordForm(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Password") self.setFixedSize(400, 300) # 初始化控件 self.label = QLabel("Enter Admin Password:") self.admin_pass_input = QLineEdit() self.admin_pass_input.setEchoMode(QtWidgets.QLineEdit.Password) self.pushButton = QPushButton("OK") # 构建布局 main_layout = QVBoxLayout() # 调整边距和间距匹配你原来的位置效果 main_layout.setContentsMargins(80, 20, 80, 20) main_layout.setSpacing(10) main_layout.addWidget(self.label) main_layout.addWidget(self.admin_pass_input) # 按钮居中排布 btn_layout = QHBoxLayout() btn_layout.addStretch() btn_layout.addWidget(self.pushButton) btn_layout.addStretch() main_layout.addLayout(btn_layout) # 给当前窗口绑定布局 self.setLayout(main_layout)
内容的提问来源于stack exchange,提问作者mik3bg
相关产品推荐
相关产品推荐

