如何读取当前QTabWidget选项卡的QTextEdit文本?

时间:2019-07-11 10:13:23

标签: python python-2.7 pyqt4 qtextedit qtabwidget

我有很多选项卡,它们只包含一个QTextEdit元素,我需要阅读当前选项卡的QTextEdit的文本。 有可能实现吗?

#!/depot/Python-2.7.6/bin/python

import sys,os,copy,re,subprocess
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Tool(QWidget):

    def __init__(self,parent=None):
        super(Tool, self).__init__(parent)
        self.tabs = QTabWidget()
        self.tabs.setTabsClosable(True)
        self.tabs.isMovable()
        self.initUI()

    def help_func(self):
        new_tab = QWidget()
        text = QTextEdit(self)
        text.setReadOnly(True)
        text.setLineWrapMode(QTextEdit.NoWrap)
        text.setText("some text")
        TextBoxlayout = QVBoxLayout()
        TextBoxlayout.addWidget(text)
        new_tab.setLayout(TextBoxlayout)
        self.tabs.addTab(new_tab,str(self.tabs.count()))
        self.tabs.setCurrentIndex(self.tabs.count()-1)

    def initUI(self):
        Tool.help_func(self)
        Tool.help_func(self)
        Tool.help_func(self)
        grid = QGridLayout(self)
        grid.addWidget(self.tabs,0,0)
        self.setLayout(grid)

我希望在标签更改信号上打印QTextEdit文本。

1 个答案:

答案 0 :(得分:2)

利用QTextEdit是TextBoxlayout的一部分这一事实,因此它是new_tab的子代,可以使用findChild()获得它:

class Tool(QWidget):
    def __init__(self, parent=None):
        super(Tool, self).__init__(parent)
        self.tabs = QTabWidget(
            tabsClosable=True, currentChanged=self.onCurrentChanged
        )
        self.initUI()

    def help_func(self):
        new_tab = QWidget()
        text = QTextEdit(readOnly=True, lineWrapMode=QTextEdit.NoWrap)
        text.setText("some text")
        TextBoxlayout = QVBoxLayout(new_tab)
        TextBoxlayout.addWidget(text)
        self.tabs.addTab(new_tab, str(self.tabs.count()))
        self.tabs.setCurrentIndex(self.tabs.count() - 1)

    def initUI(self):
        for _ in range(3):
            self.help_func()
        grid = QGridLayout(self)
        grid.addWidget(self.tabs, 0, 0)

    @pyqtSlot(int)
    def onCurrentChanged(self, ix):
        w = self.tabs.widget(ix)
        te = w.findChild(QTextEdit)
        if te is not None:
            print(te.toPlainText())