EtTerreATerre EtTerreATerre - 5 months ago 33
Python Question

PyQt5 show a file content in message window

So, i have a file info.txt, and i want to show content when i click on Info.

import sys
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication, QMessageBox
from PyQt5.QtGui import QIcon
file=open("info.txt","r")
data=file.read()


class Example(QMainWindow):
def showdialog(self):
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)

msg.setText(data)
msg.setWindowTitle("Info")
msg.show()

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

self.initUI()


def initUI(self):
textEdit = QTextEdit()
self.setCentralWidget(textEdit)

sourceAction = QAction(QIcon('info.png'), 'More informations', self)
sourceAction.setShortcut('Ctrl+I')
sourceAction.setStatusTip('More info')


self.statusBar()

sourceAction.triggered.connect(self.showdialog)

menubar = self.menuBar()
fileMenu = menubar.addMenu('&About')
fileMenu.addAction(sourceAction)

sourceAction.triggered.connect(self.showdialog)

toolbar = self.addToolBar('Exit')
toolbar.addAction(sourceAction)

self.setGeometry(300, 300, 350, 250)
self.setWindowTitle('Summoner info')
self.show()



if __name__ == '__main__':

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

file.close()


The message box doesn't show the content of the file info.txt and almost instantly disappear...
I have to add some more details because my message is mostly code...

Answer

You're defining showdialog as a method of your class Example. This

sourceAction.triggered.connect(showdialog)

however, looks for showdialog in the local and global namespace - where it isn't defined. Instead, connect the signal to the the method:

sourceAction.triggered.connect(self.showdialog)

Plus, you'll also have to take at least self as a parameter in your method. I've also added an msg.show() call - your messagebox will otherwise not become visible.

def showdialog(self):

   msg = QMessageBox(self)
   # etc...

   # actually show the message box:
   msg.show()

EDIT: Added self as parent for the messagebox - so it's not recycled.

Comments