Qt:显示或隐藏QFormLayout中包含子yout的行



如果QFormLayout的每一行都包含一个QLabel和一个QWidget,我可以显示或隐藏它的行。

showHideHeaderBtn = QCheckBox("Show")
hbox.addWidget(showHideHeaderBtn)
...
# Simple QFormLayout
self.headerOptForm = QFormLayout()
self.vbox.addLayout(self.headerOptForm)
self.ccEdit = QLineEdit()
self.headerOptForm.addRow("Cc", self.ccEdit)
self.bccEdit = QLineEdit()
self.headerOptForm.addRow("Bcc", self.bccEdit)
self.replyToEdit = QLineEdit()
self.headerOptForm.addRow("ReplyTo", self.replyToEdit)
showHideHeaderBtn.toggled.connect(lambda:
self.showHideHeaderBtn_clicked(showHideHeaderBtn,
self.headerOptForm, 2))

相应的showHideHeaderBtn_clicked由给出

def showHideHeaderBtn_clicked(self,toggleBtn,formLayout,ncol):
nrows = formLayout.rowCount()
nindex = ncol*nrows
if toggleBtn.isChecked():
# Show the lines
for idx in range(0,nindex):
widget = formLayout.itemAt(idx).widget()
widget.show()
else:
# Hide the lines
for idx in range(0,nindex):
widget = formLayout.itemAt(idx).widget()
widget.hide()
return

然而,当QFormLayout本身有这样的布局时:

self.attachForm = QFormLayout()
self.vBox.addLayout(self.attachForm)
...
hbox = QHBoxLayout()
self.attachForm.addRow('',hbox)
browseBtn = QPushButton("Open")
browseBtn.setToolTip("Select File")
browseBtn.clicked.connect(self.browseBtn_clicked)
hbox.addWidget(browseBtn)
addAttachEdit = QLineEdit()
hbox.addWidget(addAttachEdit)
delAttachBtn = QPushButton("x")
delAttachBtn.setFixedSize(15,15)
delAttachBtn.clicked.connect(self.delAttachBtn_clicked)
hbox.addWidget(delAttachBtn)

然后showHideHeaderBtn_clicked函数对于每一行都会失败(因为它有一个子布局(。如何修改showHideHeaderBtn_clicked函数以显示/隐藏QFormLayout的行?

在Qt 6.4中添加了特殊方法QtWidgets.QFormLayout.setRowVisible(layout, on)来隐藏或显示行

@musicamante对我的问题的评论帮助了我。最终的解决方案是

self.attachForm = QFormLayout()
self.vBox.addLayout(self.attachForm)
...
container = QWidget()                # New line 
self.attachForm.addRow('',container) # New line
hbox = QHBoxLayout()
# self.attachForm.addRow('',hbox)    # Old line, commented out
hbox.setContentsMargins(0,0,0,0)     # New line
container.setLayout(hbox)            # New line
browseBtn = QPushButton("Open")
browseBtn.setToolTip("Select File")
browseBtn.clicked.connect(self.browseBtn_clicked)
hbox.addWidget(browseBtn)
addAttachEdit = QLineEdit()
hbox.addWidget(addAttachEdit)
delAttachBtn = QPushButton("x")
delAttachBtn.setFixedSize(15,15)
delAttachBtn.clicked.connect(self.delAttachBtn_clicked)
hbox.addWidget(delAttachBtn)

showHideBtn_clicked()功能略微修改为

def showHideBtn_clicked(self,toggleBtn,formLayout,ncol):
nrows = formLayout.rowCount()
nindex = ncol*nrows
for idx in range(0,nindex):
widgetItem = formLayout.itemAt(idx)
if widgetItem != None:
widget = widgetItem.widget()
if toggleBtn.isChecked():
widget.show()
else:
widget.hide()

最新更新