Найти - Пользователи
Полная версия: [PyQt] Загрузка данных из файла в таблицу - проблема
Начало » GUI » [PyQt] Загрузка данных из файла в таблицу - проблема
1
g-kit
Добрый день,

есть таблица QTableView. Пытаюсь загрузить в нее из файла данные. Но что-то я пропустил и скрипт работает следующим образом: даные добавляются (появляются в таблице) только в случае если в таблице присутствуют строки (пустые или нет - не важно), т.е. данные из файла успешно вытягиваются и висят в памяти, но создать для себя ячейки в таблице не могут. Добавление пустых строк после открытия файла при пустой таблице ведет к появленннию даных в ячейках таблицы. Что я пропустил?

def loadFile(self, fileName):
exception = None
fh = None
self.fileName = QtCore.QString(fileName)
try:
if self.fileName.isEmpty():
raise IOError, "no fileName specified for loading"
fh = QtCore.QFile(self.fileName)
if not fh.open(QtCore.QIODevice.ReadOnly):
raise IOError, unicode(fh.errorString())
stream = QtCore.QDataStream(fh)
magic = stream.readInt32()
if magic != MAGIC_NUMBER:
raise IOError, "unrecognized file type"
fileVersion = stream.readInt16()
if fileVersion != FILE_VERSION:
raise IOError, "unrecognized file type version"
stream.setVersion(QtCore.QDataStream.Qt_4_5)
self.ships = []
while not stream.atEnd():
name = QtCore.QString()
owner = QtCore.QString()
country = QtCore.QString()
description = QtCore.QString()
stream >> name >> owner >> country >> description
teu = stream.readInt32()
self.ships.append(Ship(name, owner, country, description, teu))
self.dirty = False
except (IOError, OSError), e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception
спасибо,
-вадим
dartNNN
Код какой-то маленький, мало что смог понять и совсем не видно где идет добавление в таблицу. По сути надо бы проверить режим отправки данных (manual submit случайно не указан?) Вобщем покажите весь код тогда и подумаю
g-kit
весь код скрипта. Пока имеет модель QTableView, умеет вставлять, удалять строки, сохранять, но пока не загружает данные в /из файла.

спасибо,
-вадим

#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys

# Set API version (old - 1, new - 2)
import sip; sip.setapi("QVariant", 1); sip.setapi("QString", 1)

from PyQt4 import QtCore, QtGui
from ui_trianon_002 import Ui_MainWindow

MAGIC_NUMBER = 0x570C4
FILE_VERSION = 1

NAME, OWNER, COUNTRY, DESCRIPTION, TEU = range(5)


class MainForm (QtGui.QMainWindow):

def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.model = model_table_1_frame_1(self.ui.table_1_frame_1)
self.ui.table_1_frame_1.setModel(self.model)

self.connect(self.ui.AddShipButton, QtCore.SIGNAL("clicked()"), self.AddShip)
self.connect(self.ui.RemoveShipButton, QtCore.SIGNAL("clicked()"), self.RemoveShip)
self.connect(self.ui.SaveButton, QtCore.SIGNAL("clicked()"), self.accept)
self.connect(self.ui.openFileButton, QtCore.SIGNAL("clicked()"), self.openFile)

def AddShip(self):
row = self.model.rowCount()
self.model.insertRows(row)
index = self.model.index(row, 0)
frame = self.ui.table_1_frame_1
frame.setCurrentIndex(index)
frame.edit(index)

def RemoveShip(self):
frame = self.ui.table_1_frame_1
index = frame.currentIndex()
if not index.isValid():
return
if QtGui.QMessageBox.question(self, "Ships-Remove", "Remove this item?", QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) == QtGui.QMessageBox.No:
return
row = index.row()
self.model.removeRows(row)

def accept(self):
if self.model.dirty and \
QtGui.QMessageBox.question(self, "Ships - Save?",
"Save unsaved changes?",
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
try:
self.model.saveFile()
except IOError, e:
QtGui.QMessageBox.warning(self, "Ships - Error", "Failed to save: %s" % e)

def openFile(self):
fileName = QtGui.QFileDialog.getOpenFileName(self, "Load Data", "/home/", "Trianon Project (*.tri)")
if fileName.isEmpty():
raise IOError, "no fileName specified for loading at openFile module"
self.model.loadFile(fileName)

class Ship(object):

def __init__(self, name, owner, country, description, teu):
self.name = QtCore.QString(name)
self.owner = QtCore.QString(owner)
self.country = QtCore.QString(country)
self.description = QtCore.QString(description)
self.teu = teu


class model_table_1_frame_1(QtCore.QAbstractTableModel):

def __init__(self, fileName = QtCore.QString()):
super (model_table_1_frame_1, self).__init__()
self.ships = []
self.fileName = fileName
self.dirty = True
self.owners = set ()
self.countries = set()

def rowCount (self, index=QtCore.QModelIndex()):
return len(self.ships)


def columnCount (self, index=QtCore.QModelIndex()):
return 5


def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if role != QtCore.Qt.DisplayRole:
return
if orientation == QtCore.Qt.Horizontal:
if section == NAME:
return (QtGui.QApplication.translate("MainWindow", "Найменування", None, QtGui.QApplication.UnicodeUTF8))
elif section == OWNER:
return "Owner"
elif section == COUNTRY:
return "Country"
elif section == DESCRIPTION:
return "Description"
elif section == TEU:
return "TEU"
return int(section + 1)


def data (self, index, role=QtCore.Qt.DisplayRole):
if index.isValid() and 0 <= index.row() < len(self.ships):
ship = self.ships [index.row()]
column = index.column()
if role == QtCore.Qt.DisplayRole:
if column == NAME:
return QtCore.QVariant(ship.name)
elif column == OWNER:
return QtCore.QVariant(ship.owner)
elif column == COUNTRY:
return QtCore.QVariant(ship.country)
elif column == DESCRIPTION:
return QtCore.QVariant(ship.description)
elif column == TEU:
return QtCore.QVariant(ship.teu)
return


def flags(self, index):
if not index.isValid():
return QtCore.Qt.ItemIsEnabled
return QtCore.Qt.ItemFlags(QtCore.QAbstractTableModel.flags(self, index)|QtCore.Qt.ItemIsEditable)


def setData (self, index, value, role=QtCore.Qt.DisplayRole):
if index.isValid() and 0 <= index.row() < len (self.ships):
ship = self.ships [index.row()]
column = index.column()
if column == NAME:
ship.name = value.toString()
elif column == OWNER:
ship.owner = value.toString()
elif column == COUNTRY:
ship.country = value.toString()
elif column == DESCRIPTION:
ship.description = value.toString()
elif column == TEU:
ship.TEU = value.toInt()
self.dirty = True
return True
return False


def insertRows (self, position, rows=1, index=QtCore.QModelIndex()):
self.beginInsertRows(QtCore.QModelIndex(), position, position + rows - 1)
for row in range(rows):
self.ships.insert(position + row, Ship("Unknown", "Unknown", "Unknown", "Unknown", None))
self.endInsertRows()
self.dirty = True
return True


def removeRows(self, position, rows=1, index=QtCore.QModelIndex()):
self.beginRemoveRows(QtCore.QModelIndex(), position, position + rows - 1)
self.ships = self.ships[:position] + self.ships [position + rows:]
self.endRemoveRows()
self.dirty = True
return True

def loadFile(self, fileName):
exception = None
fh = None
self.fileName = QtCore.QString(fileName)
try:
if self.fileName.isEmpty():
raise IOError, "no fileName specified for loading"
fh = QtCore.QFile(self.fileName)
if not fh.open(QtCore.QIODevice.ReadOnly):
raise IOError, unicode(fh.errorString())
stream = QtCore.QDataStream(fh)
magic = stream.readInt32()
if magic != MAGIC_NUMBER:
raise IOError, "unrecognized file type"
fileVersion = stream.readInt16()
if fileVersion != FILE_VERSION:
raise IOError, "unrecognized file type version"
stream.setVersion(QtCore.QDataStream.Qt_4_5)
self.ships = []
while not stream.atEnd():
name = QtCore.QString()
owner = QtCore.QString()
country = QtCore.QString()
description = QtCore.QString()
stream >> name >> owner >> country >> description
teu = stream.readInt32()
self.ships.append(Ship(name, owner, country, description, teu))
except (IOError, OSError), e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception


def saveFile(self):
exception = None
fh = None
self.fileName = QtCore.QString()
try:
if self.fileName.isEmpty():
self.fileName = QtGui.QFileDialog.getSaveFileName(None, "Ships - Choose Save File", "/home/", "Trianon project (*.tri)")
fh = QtCore.QFile(self.fileName)
if not fh.open(QtCore.QIODevice.WriteOnly):
raise IOError, unicode(fh.errorString())
stream = QtCore.QDataStream(fh)
stream.writeInt32(MAGIC_NUMBER)
stream.writeInt16(FILE_VERSION)
stream.setVersion(QtCore.QDataStream.Qt_4_5)
for ship in self.ships:
stream << QtCore.QString(ship.name) << QtCore.QString(ship.owner) << QtCore.QString(ship.country) << QtCore.QString(ship.description)
stream.writeInt32(ship.teu)
self.dirty = False
except IOError, e:
exception = e
finally:
if fh is not None:
fh.close()
if exception is not None:
raise exception



if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainForm()
myapp.show()
sys.exit(app.exec_())
villager
может стоит попробовать после загрузки сделать reset модели?
g-kit
именно так!

спасибо,
-вадим

ЗЫ Ночью почти пришел к тому же… :)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB