Avo Asatryan
Avo Asatryan

Reputation: 414

How to read QTextEdit text of current QTabWidget's tab?

I have many tabs and they contain only one QTextEdit element and i need to read QTextEdit's text of current tab. Is it possible to realize?

#!/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)

I wish to print the QTextEdit text on tab change signal.

Upvotes: 1

Views: 340

Answers (1)

eyllanesc
eyllanesc

Reputation: 243973

Taking advantage of the fact that the QTextEdit is part of the TextBoxlayout so it is a child of new_tab it can be obtained using 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())

Upvotes: 2

Related Questions