【发布时间】:2019-02-06 10:22:43
【问题描述】:
我正在尝试为我的 python 程序创建一个 GUI。我需要的工具之一是文本输入框。
现在,我想要这个框的文本标签,上面写着“请插入文本”。是否有添加标签的功能,该标签默认显示在输入文本框中,并在用户单击框输入时消失?
我不介意使用 qt 设计器或 pyqt5 编码。
谢谢你们。
【问题讨论】:
我正在尝试为我的 python 程序创建一个 GUI。我需要的工具之一是文本输入框。
现在,我想要这个框的文本标签,上面写着“请插入文本”。是否有添加标签的功能,该标签默认显示在输入文本框中,并在用户单击框输入时消失?
我不介意使用 qt 设计器或 pyqt5 编码。
谢谢你们。
【问题讨论】:
placeholderText : QString
此属性保存行编辑的占位符文本
import sys
from PyQt5.QtWidgets import QLineEdit, QVBoxLayout, QApplication, QWidget
class Test(QWidget):
def __init__(self):
super().__init__()
self.lineEdit = QLineEdit(placeholderText="Please insert texts.") # <---
vbox = QVBoxLayout(self)
vbox.addWidget(self.lineEdit)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Test()
w.show()
sys.exit(app.exec_())
【讨论】:
我和你一样是初学者,我的英语不太好。但我建议你使用 Qt Designer。绘制应用程序更容易、更快。我正在使用 pyside2 项目,建议您阅读文档,了解您想在 PySide2 项目和 Qt 项目中使用的每个小部件。试试下面的代码
import sys
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QDialog
from PySide2.QtWidgets import QTextEdit
from PySide2.QtWidgets import QVBoxLayout
from PySide2.QtCore import Qt
class MainDialog(QDialog):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
# Create Widget TextEdit
self.text = QTextEdit()
# I think that you wanna this function in your program
# https://doc.qt.io/qtforpython/PySide2/QtWidgets/QLineEdit.html?highlight=qlineedit#PySide2.QtWidgets.PySide2.QtWidgets.QLineEdit.setPlaceholderText
# http://doc.qt.io/qt-5/qlineedit.html#placeholderText-prop
self.text.setPlaceholderText('''Yes! this is exactly what I want!
Thank you, what if you have a big text box (more than 10 lines) and
you want to scale up the place holder and align it in center?? ''')
# https://doc.qt.io/qtforpython/PySide2/QtWidgets/QLineEdit.html?highlight=qlineedit#PySide2.QtWidgets.PySide2.QtWidgets.QLineEdit.setAlignment
# http://doc.qt.io/qt-5/qlineedit.html#alignment-prop
self.text.setAlignment(Qt.AlignCenter)
# Layout
layout = QVBoxLayout()
layout.addWidget(self.text)
self.setLayout(layout)
def main():
app = QApplication()
mainDialog = MainDialog()
mainDialog.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
【讨论】: