PYQT5 从 Window 标题获取文本?

PYQT5 Getting text from the Window title?

我希望我有一个简单的问题。我有一个 pyqt mainwindow,它有一个 sub-windows 的 mdi 区域。我希望能够从当前 sub-window 中获取标题文本并将其设置为一个变量。

我这样做的原因是,当您单击我的主要 window 的其他部分时,我有 mdi sub-windows 打开以编辑已输入的数据.我希望用户能够一次打开和编辑多组数据,我正在为标题栏中的数据设置目录键。我认为这将是区分当前正在编辑的数据集的好方法。

我不确定这是否是实现我想要的目标的最佳方式,甚至是一种好方式。如果有另一种更好的方法,我很想听听。

感谢您的宝贵时间。

QMdiArea provides a method QMdiArea::activeSubWindow() as well as a signal QMdiArea::subWindowActivated().

QMdiSubWindow is (directly) derived from QWidget which in turn provides a property QWidget::windowTitle.

综上所述,应该可以。

我准备了一个 MCVE 作为 "proof of concept"(并训练我的 Python/PyQt 技能)。

示例代码testQMDIActiveSubWindow.py:

#!/usr/bin/python3

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMdiArea, QMdiSubWindow

def updateActiveChild(subWindow):
  win.setWindowTitle("MDI Test: '%s'" % subWindow.windowTitle())

if __name__ == '__main__':
  app = QApplication(sys.argv)
  # build GUI
  win = QMainWindow()
  win.resize(640, 480)
  mdiArea = QMdiArea()
  for title in ["Data:1", "Data:2", "Data:3", "Data:n"]:
    mdiChild = QMdiSubWindow()
    mdiChild.setWindowTitle(title)
    mdiArea.addSubWindow(mdiChild)
  mdiArea.tileSubWindows()
  win.setCentralWidget(mdiArea)
  win.show()
  updateActiveChild(mdiArea.activeSubWindow())
  # install signal handlers
  mdiArea.subWindowActivated.connect(updateActiveChild)
  # exec. application
  sys.exit(app.exec_())

我在 python3, cygwin64, Windows 10 (64 位):

中测试过

活动sub-window的标题反映在主要window的标题中。