I have two files, one for my main window, which has one image and one button and one for a new window. What I want it to do is that when I push the button from my main window, it lets me load a file and show it in a TextEdit
widget in the new window
so here I have the files I'm using:
MainWindow.py
import sys
import os
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QPushButton, QVBoxLayout, QTextEdit, QHBoxLayout, QLabel, QMainWindow, QAction, QFileDialog
class Window(QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.img = QLabel()
self.relleno=QLabel()
self.btn_load = QPushButton('Load')
self.width = 400
self.height = 150
self.init_ui()
def init_ui(self):
self.img.setPixmap(QtGui.QPixmap("someimage.png"))
h_layout = QHBoxLayout()
v_layout = QVBoxLayout()
h_final = QHBoxLayout()
h_layout.addWidget(self.img)
v_layout.addWidget(self.btn_load)
h_final.addLayout(h_layout)
h_final.addLayout(v_layout)
self.btn_load.clicked.connect(self.loadafile)
self.setLayout(h_final)
self.setWindowTitle('This is main window')
self.setGeometry(600,150,self.width,self.height)
self.show()
def loadafile(self):
filename = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
with open(filename[0], 'r') as f:
file_text = f.read()
return file_text
def main():
app = QApplication(sys.argv)
main = Window()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
NewWindow.py
import os
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTextEdit, QVBoxLayout
from MainWindow import loadafile
info=loadafile()
class SecondWindow(QWidget):
def __init__(self):
super(SecondWindow, self).__init__()
self.text = QTextEdit(self)
self.init_ui()
def init_ui(self):
v_layout = QVBoxLayout()
v_layout.addWidget(self.text)
self.setLayout(v_layout)
self.setText(info)
self.setWindowTitle('Opened Text')
self.show()
app = QApplication(sys.argv)
shower = SecondWindow()
sys.exit(app.exec_())
I think the loadafile
does return my file_text
variable but I don't know how to open the new window from there. I think I need to use a destructor for main window and then show the new window but I'm not sure of how to do this (This is the first time I try OOP)