0

My Code has 2 problems.

  1. I want QPushButton is upper than QTextBrowser.
  • But, I can't. You can check image. enter image description here.
  1. When I click QPushButton, I want to change QTextBrowser's Text.
  • But, I has an error. -> Error message: 'MyApp' object has no attribute 'text_area'

This is my code. I think I don't have Python programming process.

# test.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QTextBrowser

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn2 = QPushButton(self)
        btn2.setText('Button&2')
        btn2.setGeometry(20,20,100,100)
        btn2.clicked.connect(self.callme)

        # Add QTextBrowser
        text_area = QTextBrowser(self)
        text_area.setGeometry(120, 160, 270, 120)
        text_area.setText('Before Edit')

        vbox = QVBoxLayout()
        vbox.addWidget(btn2)

        self.setLayout(vbox)
        self.setWindowTitle('QPushButton')
        self.setGeometry(200, 200, 500, 600)
        self.show()

    def callme(self):
        self.text_area.setText('After Edit')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Yoon
  • 1

1 Answers1

0

Basically, the problem is that you used text_edit at the top, but self.text_edit at the bottom. Then, to put the button at the top, set the vbox alignment to the top using vbox.setAlignment(Qt.AlignTop)

Try this:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QTextBrowser

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn2 = QPushButton(self)
        btn2.setText('Button&2')
        btn2.setGeometry(20,20,100,100)
        btn2.clicked.connect(self.callme)

        # Add QTextBrowser
        self.text_area = QTextBrowser(self)
        self.text_area.setGeometry(120, 160, 270, 120)
        self.text_area.setText('Before Edit')

        vbox = QVBoxLayout()
        vbox.addWidget(btn2)
        vbox.setAlignment(Qt.AlignTop)

        self.setLayout(vbox)
        self.setWindowTitle('QPushButton')
        self.setGeometry(200, 200, 500, 600)
        self.show()

    def callme(self):
        self.text_area.setText('After Edit')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())
halfer
  • 19,824
  • 17
  • 99
  • 186
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24