X
X
x_GG2021-12-18 16:35:13
Python
x_GG, 2021-12-18 16:35:13

PyQT5. Opening a file in a textEdition in a child window. How to implement?

I don’t really understand PyQT, I just started studying. Unable to implement 'open' function. You need to bind the main window to the "text" window so that you can pass the text to another class's textEdit1 on save. Because when I try to do it via self.win.textEdit1.setText(text1) it throws an error "AttributeError: 'Ui_Text' object has no attribute 'textEdit1'". I understand that the class of the main window cannot change the value of the class of another window. How can this be fixed?

Part of code from design(design.ui)

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.NonModal)
        MainWindow.setEnabled(True)
        MainWindow.resize(1012, 729)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(1012, 570))
        font = QtGui.QFont()


Child window 1: help.py
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Help(object):
    def setupUi(self, Help):
        Help.setObjectName("Help")
        Help.resize(700, 501)
        self.formLayout = QtWidgets.QFormLayout(Help)
        self.formLayout.setContentsMargins(0, 0, 0, 0)
        self.formLayout.setHorizontalSpacing(0)
        self.formLayout.setObjectName("formLayout")
        self.listWidget = QtWidgets.QListWidget(Help)
        self.listWidget.setEnabled(True)
        self.listWidget.setMinimumSize(QtCore.QSize(700, 501))
        self.listWidget.setResizeMode(QtWidgets.QListView.Fixed)
        self.listWidget.setObjectName("listWidget")
        self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.listWidget)

        self.retranslateUi(Help)
        QtCore.QMetaObject.connectSlotsByName(Help)

    def retranslateUi(self, Help):
        _translate = QtCore.QCoreApplication.translate
        Help.setWindowTitle(_translate("Help", "Dialog"))


Child window 2 to which data should be transferred from txt: text.py

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Text(object):
    def setupUi(self, Text):
        Text.setObjectName("Text")
        Text.resize(958, 736)
        Text.setIconSize(QtCore.QSize(30, 30))
        self.centralwidget = QtWidgets.QWidget(Text)
        self.centralwidget.setMinimumSize(QtCore.QSize(775, 583))
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(7)
        self.gridLayout.setObjectName("gridLayout")
        self.textEdit1 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit1.setObjectName("textEdit1")
        self.textEdit1.setText('')
        text = self.textEdit1
        self.gridLayout.addWidget(self.textEdit1, 0, 0, 1, 1)
        Text.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(Text)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 26))
        self.menubar.setObjectName("menubar")
        Text.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(Text)
        self.statusbar.setObjectName("statusbar")
        Text.setStatusBar(self.statusbar)

        self.retranslateUi(Text)
        QtCore.QMetaObject.connectSlotsByName(Text)

    def retranslateUi(self, Text):
        _translate = QtCore.QCoreApplication.translate
        Text.setWindowTitle(_translate("Text", "MainWindow"))


def main():
    app = QApplication(sys.argv)
    window = Ui_Text()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':


And the app.py file where I initialize the interface etc.

from sys import argv
from typing import List

from PyQt5 import QtWidgets, Qt, QtCore
from PyQt5.QtMultimedia import QSound
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp, QTextEdit, QDialog, QFileDialog
from PyQt5.QtGui import QFontDatabase, QIcon
from PyQt5 import QtGui
from PyQt5.QtCore import QCoreApplication
import design
import Help
import text

class Text(QMainWindow,text.Ui_Text):
    def __init__(self, parent=None):
        """Метод инициализации интерфейса."""
        super(Text, self).__init__(parent)
        self.setupUi(self)
        self.show()


class Helped(QDialog, Help.Ui_Help):
    def __init__(self, parent=None):
        """Метод инициализации интерфейса."""
        super(Helped, self).__init__(parent)
        self.setupUi(self)
        self.show()


class ExampleApp(QMainWindow, design.Ui_MainWindow):
    def __init__(self,parent=None):
        """Метод инициализации интерфейса."""
        super(ExampleApp, self).__init__(parent)
        QFontDatabase.addApplicationFont('fonts/circe.ttf')
        QFontDatabase.addApplicationFont('fonts/circe-bold.ttf')
        QFontDatabase.addApplicationFont('fonts/circe-extrabold.ttf')
        self.setupUi(self)
        self.pushButton.clicked.connect(self.count)
        self.setWindowIcon(QIcon('calculator.png'))
        self.action_Quit.triggered.connect(self.close)
        self.menuFile.triggered.connect(self.selected)
        self.action_Document.triggered.connect(self.dialog)
        self.action_Save.triggered.connect(self.save)
        self.actionSave_as.triggered.connect(self.save_as)
        self.action_Open.triggered.connect(self.file_open())

        self.Sound = QSound('sound_button.wav', self)
        self.pushButton.clicked.connect(self.Sound.play)
        self.action_Quit.triggered.connect(self.Sound.play)
        self.menuFile.triggered.connect(self.Sound.play)
        self.action_Document.triggered.connect(self.Sound.play)
        self.menu_Help.triggered.connect(self.Sound.play)
        self.show()
        self.name = "save.txt"

    def okno2(self):
        self.okno = Helped()
        self.okno.show()

    def file_open(self):
            fname = QFileDialog.getOpenFileName(self, 'Open file', '', '*.txt')[0]
            self.win = text.Ui_Text()
            if len(fname) > 0:
                f = open(fname,'r')
                with f:
                    text1 = f.read()
                    self.win.textEdit1.setText(text1)
            self.okno2()


    def save_as(self):
        self.name = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File', '', '(*.txt')[0]
        self.save()

    def save(self):
        a_field = (
        self.a_field.text(), self.b_field.text(), self.h_field.text(), self.as_field.text(), self.m_field.text(),
        self.class_bt.currentText(), self.class_ar.currentText(), self.answer_text.toPlainText())
        if a_field[0] == '' or a_field[1] == '' or a_field[2] == '' or a_field[3] == '' or a_field[4] == ''or a_field[7] == '':
            reply = QtWidgets.QMessageBox.information(self, "Save", "Enter the data click the calculate button to save the data",
                                                   QtWidgets.QMessageBox.Yes)
        else:
            if len(self.name)>0:
                with open(self.name,'a') as f:
                    f.write('а= '+a_field[0]+' мм'+'\n'+'b= '+a_field[1]+' мм'+'\n'+'h= '+ a_field[2]+' мм'+'\n'+'As= '+ a_field[3]+' мм2'+'\n'+'M= '+ a_field[4]+' kH*M'+'\n'+'Класс бетона: '+ a_field[5]+'\n'+'Класс арматуры: '+ a_field[6]+'\n'+'Прочность арматуры: '+ a_field[7]+'\n \n')

    def dialog(self):
        dialog = QtWidgets.QDialog()
        dialog.ui = Help.Ui_Help()
        dialog.ui.setupUi(dialog)
        dialog.exec_()
        dialog.show()


.. calculations are going on here, etc.

Another question is of interest. I have widget click function self.pushButton.clicked.connect(self.count), how can i add another function when right click. Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-18
@Vindicar

self.win = text.Ui_Text()
Are you sure that when the window object is constructed, its setupUi() method will be automatically called?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question