Issue
I'm trying to write an app to deal with data saving and loading with QTableWidget.
I want to write a more complex app, so, I use many pyqt classes to define different pages. Here is the code:
import sys
from PyQt4 import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self)
load_file = QtGui.QAction("Load", self)
load_file.triggered.connect(self.loadFile)
save_file = QtGui.QAction("Save", self)
save_file.triggered.connect(self.saveFile)
menubar = self.menuBar()
file = menubar.addMenu('&File')
file.addAction(load_file)
file.addAction(save_file)
table = Table()
self.setCentralWidget(table)
def loadFile(self):
load_file = QtGui.QFileDialog.getOpenFileName(self, "Open file", "./", "All files(*)")
if load_file:
with open(load_file, "r") as load_data:
data = eval(load_data.read())
Table().filling(data)
def saveFile(self):
save_file = QtGui.QFileDialog.getSaveFileName(self, "Save file", "./", "All files(*)")
if save_file:
with open(save_file, "w") as save_data:
save_data.write(repr(DATA))
class Table(QtGui.QTableWidget):
def __init__(self, parent = None):
QtGui.QTableWidget.__init__(self)
self.setRowCount(4)
self.setColumnCount(2)
self.itemChanged.connect(self.getData)
def getData(self):
data = []
for row in range(4):
row_data = []
for col in range(2):
if self.item(row, col):
text = self.item(row, col).text()
row_data.append(str(text))
else:
row_data.append("")
data.append(row_data)
global DATA
DATA = data
def filling(self, data):
for row in range(4):
for col in range(2):
new_item = QtGui.QTableWidgetItem("")
self.setItem(row, col, new_item)
self.item(row, col).setText(data[row][col])
app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
The app can save data filt in the QTableWidget, but cannot show the loaded data.
I want to know what the problem is.
Solution
The problem is caused because when calling Table().filling()
you are creating and filling another table, it is appropriate to make the table member of the class.
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
[...]
self.table = Table(self)
self.setCentralWidget(self.table)
def loadFile(self):
load_file = QtGui.QFileDialog.getOpenFileName(self, "Open file", "./", "All files(*)")
if load_file:
with open(load_file, "r") as load_data:
data = eval(load_data.read())
print(data)
self.table.filling(data)
[...]
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.