为了实现这个功能,我们需要创建一个自定义的界面,其中包括:
- 一个父文本框,用户可以在其中输入信息。
- 一个加号按钮,点击后可以添加一个新的子文本框。
- 当添加子文本框时,父文本框的高度会自动调整以适应新增的子文本框。
- 加号按钮始终保持在子文本框的下方。
我们可以通过使用 QVBoxLayout
来管理布局,并通过动态创建新的文本框和按钮来实现这一功能。每次点击加号按钮时,都会创建新的子文本框,并在父容器的布局中进行更新。
实现代码:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Dynamic TextBox Example")
self.setGeometry(100, 100, 400, 300)
# 创建主布局
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.layout = QVBoxLayout(self.main_widget)
# 创建父文本框
self.parent_textbox = QTextEdit(self)
self.parent_textbox.setPlaceholderText("输入必要信息")
self.layout.addWidget(self.parent_textbox)
# 创建加号按钮
self.add_button = QPushButton("+", self)
self.add_button.clicked.connect(self.add_child_textbox)
self.layout.addWidget(self.add_button)
self.child_textboxes = [] # 用于存储子文本框
def add_child_textbox(self):
"""点击加号按钮时,添加一个子文本框"""
child_layout = QHBoxLayout()
# 创建子文本框
child_textbox = QTextEdit(self)
child_textbox.setPlaceholderText("请输入子项信息")
self.child_textboxes.append(child_textbox)
# 创建每个子文本框右侧的加号按钮
add_button = QPushButton("+", self)
add_button.clicked.connect(self.add_child_textbox)
# 将子文本框和按钮放入一个水平布局
child_layout.addWidget(child_textbox)
child_layout.addWidget(add_button)
# 添加到主布局
self.layout.addLayout(child_layout)
# 调整父文本框的高度(随着子文本框数量变化)
self.adjust_parent_textbox_height()
def adjust_parent_textbox_height(self):
"""根据子文本框的数量自动调整父文本框的高度"""
# 设置一个基本的高度单位(每个子文本框占用的高度)
base_height = 30
additional_height = len(self.child_textboxes) * base_height
# 设置父文本框的高度,最小为原始高度
self.parent_textbox.setFixedHeight(max(100, 50 + additional_height))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
代码解析:
-
QTextEdit
:文本框控件,用户可以在其中输入信息。每次添加子文本框时,都会创建一个新的QTextEdit
。 -
QPushButton
:加号按钮,每个子文本框下方都会有一个加号按钮,点击时可以动态添加新的子文本框。 -
QVBoxLayout
和QHBoxLayout
:用于管理布局。QVBoxLayout
管理父文本框和子文本框的垂直布局,QHBoxLayout
用来将每个子文本框与加号按钮水平布局。 -
动态调整父文本框的高度:每当点击加号按钮,都会根据当前子文本框的数量来调整父文本框的高度。每个子文本框和加号按钮的组合占用一定的高度(在这里设置为 30 像素)。
adjust_parent_textbox_height
函数计算当前子文本框的总高度并调整父文本框的高度。 -
self.child_textboxes
:用来跟踪当前已创建的子文本框,计算其数量来动态调整父文本框的高度。
功能:
- 用户可以输入必要信息到父文本框中。
- 点击父文本框右侧的加号按钮时,会动态添加一个新的子文本框,并且加号按钮会始终位于最后一个子文本框的下方。
- 父文本框的高度会随着子文本框的增加而自动调整,以确保所有内容都能展示。
你可以根据需要调整每个文本框和按钮的外观或行为。