python - 动态添加小部件python
问题描述
我有这两个 python 脚本,我想将它们合并到一个窗口中。基本上,在选中按钮时将小部件添加到窗口。这是主窗口
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.checkBox = QtWidgets.QCheckBox(Form)
self.checkBox.setGeometry(QtCore.QRect(40, 40, 171, 21))
self.checkBox.setObjectName("checkBox")
// when checkbox is true add widget
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.checkBox.setText(_translate("Form", "render frame range"))
这是我要添加的小部件
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(400, 300)
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 120, 113, 20))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(Form)
self.lineEdit_2.setGeometry(QtCore.QRect(200, 120, 113, 20))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(140, 120, 47, 13))
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(30, 160, 131, 31))
self.pushButton.setObjectName("pushButton")
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", "to"))
self.pushButton.setText(_translate("Form", "Render Sequence"))
我知道我需要将小部件作为主窗口的父级,但我不知道如何。当复选框为真时,我希望添加小部件。如果复选框为假,我希望删除小部件。我见过 c++ 的例子,但不是 python 的例子。如果有人可以帮助我或指出我正确的方向,那就太好了。
解决方案
您不需要添加/删除小部件。您可以根据复选框的状态隐藏或显示它。
将信号连接QCheckBox::clicked
到插槽QWidget::setVisible
:
class MainWindow(QWidget):
def __init__(self, parent=None, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
self.resize(400, 300)
self.checkBox = QCheckBox("Hide/show", self)
self.checkBox.setGeometry(QRect(40, 40, 171, 21))
self.widgetToManage = QLabel("Hello world!", self)
self.widgetToManage.hide() # the checkbox is unchecked by default.
# When the checkbox is checked, the widget is visible.
self.checkBox.clicked.connect(self.widgetToManage.setVisible)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
app.setActiveWindow(window)
window.show()
sys.exit(app.exec_())
推荐阅读
- c++ - 如何使用 SV-DPI 将数据从 C/C++ 数组复制到整个 SV 数组?
- bash - 如何使用 Terraform 将文件夹/文件从 Git 存储库上传到 S3 存储桶?
- reshape - ValueError:密集层的输入 0 与层不兼容:输入形状的预期轴 -1 的值为 6,但此处输入的形状为(无,8)
- python - Scrapy Item Loader 不能正确地从回调中产生
- vb.net - 使用该文件后尝试删除文件,使用Visual Basic
- angular - 如何通过传递下拉值的 id 自动选择下拉值?
- javascript - 为什么我有时不需要使用'get'而其他时候需要使用'get'进行过滤?
- c++ - 无法将 Arduino NANO 33 IOT 连接到 NEO 6M GPS 模块
- devexpress-mvc - 在网格视图 dev express 中多选 bobox
- laravel - Discord API(将角色授予公会成员)返回 405 错误