here i changed this code according to my program,i got an error can you please help me how to rectify this error
def save_file(self):
self.contents =QtGui.QTextEdit()
self.w = QtGui.QWidget()
self.lay = QtGui.QVBoxLayout()
filename, filter = QtGui.QFileDialog.getOpenFileName(parent=self, caption='Open file', dir='.', filter='csv file(*.csv)')
if filename:
self.contents.setText(filename.read())
self.lay.addWidget(self.contents)
self.w.setLayout(self.lay)
self.scrollArea.setWidget(self.w)
AttributeError: 'unicode' object has no attribute 'read'
You have the following errors:
scrollArea
is a widget that is not part of the w
widget, so it will not show, so there are 2 possible solutions: make it son of w and resize its size manually, or use a layout, in this case use the second.
When you read a file with f.read()
you delete it from the buffer f, that is, if you call f.read()
it will not return anything since the cursor is at the end of the file, so it is printed on the console but it will not show up in the QTextEdit.
You have some typographical errors.
Considering the above, the solution is as follows:
import sys
from PyQt4 import QtGui
if __name__ == '__main__':
a = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
lay = QtGui.QVBoxLayout(w)
scrollArea = QtGui.QScrollArea(widgetResizable=True)
lay.addWidget(scrollArea)
textEdit = QtGui.QTextEdit()
scrollArea.setWidget(textEdit)
filename = QtGui.QFileDialog.getOpenFileName(w, 'Open File', '/')
if filename:
with open(filename, 'r') as f:
textEdit.setText(f.read())
w.resize(320, 240)
w.show()
sys.exit(a.exec_())