python - 使用 itemAt 从 QFormLayout 中的 QLineEdit 获取文本

标签 python python-3.x pyqt pyqt5 qformlayout

我目前正在开发一个程序,在 QFormLayout 中,我有两列 QLineEdits。我将第一列存储在列表中(这意味着它们很容易访问),而第二列未存储在变量或列表中。我试图访问第二列中 QLineEdits 的文本,但总是遇到错误。

我目前无意使用第二个列表/字典来授予对第二列的访问权限,因为使用 getWidgetPosition 和 itemAt 函数应该提供访问这些值的更简单途径。

from PyQt5.QtWidgets import *

app = QApplication([])
window = QWidget()

layout = QFormLayout()
entry1 = QLineEdit()
layout.addRow(entry1,QLineEdit())

ePos = layout.getWidgetPosition(entry1)
text = layout.itemAt(ePos[1],ePos[0]+1).text()
print(text)


window.setLayout(layout)
window.show()
app.exec_()

上面的代码只是一个接近于我尝试使用的代码的示例。出于某种原因,无法访问 QLineEdits 第二列的文本,因为我收到此错误消息:

Traceback (most recent call last):
    File "sampleProblem.py", line 11, in <module>
      text = layout.itemAt(ePos[1],ePos[0]+1).text()
 AttributeError: 'QWidgetItem' object has no attribute 'text'

最佳答案

itemAt()布局的方法返回 QLayoutItem , QLayoutItem封装另一个布局或另一个小部件,然后要获取小部件(在您的情况下为 QLineEdit),您必须使用 widget()方法,然后只获取文本。

import sys
from PyQt5 import QtWidgets

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QWidget()
    layout = QtWidgets.QFormLayout(window)
    entry1 = QtWidgets.QLineEdit()
    layout.addRow(entry1, QtWidgets.QLineEdit())

    i, j = layout.getWidgetPosition(entry1)
    widget_item = layout.itemAt(i, j+1)
    widget = widget_item.widget()
    text = widget.text()
    print(text)

    window.show()
    sys.exit(app.exec_())

关于python - 使用 itemAt 从 QFormLayout 中的 QLineEdit 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57171474/

相关文章:

python-3.x - Python Scipy 模块的 HIGHs 文档

python - django 时间不能正常工作

python - 如何将 python 程序与网络连接

python - 在Python的支配模块中处理文本和换行符

python - PyQt5 中 QAbstractTableModel 给定行号的特定表行的背景颜色

python - 我想使用 pyqt5 的拖放方法获取并显示图像

python - PyQt 声子音频播放器

Python:字典推导式:使用旧字典 id 中的新值创建新字典

python - 在本地主机上运行 python 脚本

python - Request.get 突然开始遇到 "Temporary failure in name resolution"错误