使用文件属性在PyQt中填充表

时间:2012-07-12 18:01:56

标签: python pyqt qtablewidget

我正在尝试使用脚本中其他位置打开的文件的属性填充QTableWidget。我已使用以下代码成功设置了从文件中读入的文件属性:

class FileHeader(object):

fileheader_fields=(
    "filetype","fileversion","numframes",
    "framerate","resolution","numbeams",
    "samplerate","samplesperchannel","receivergain",
    "windowstart","winlengthsindex","reverse",
    "serialnumber","date","idstring","ID1","ID2",
    "ID3","ID4","framestart","frameend","timelapse",
    "recordInterval","radioseconds","frameinterval","userassigned")

fileheader_formats=(
    'S3','B','i4','i4','i4','i4','f','i4','i4','i4',
    'i4','i4','i4','S32','S256','i4','i4','i4','i4',
    'i4','i4','i4','i4','i4','i4','S136')

IMAGE_HEADER_BYTES = 256
IMAGES_DATA_BYTES = 49152

def __init__(self,filename=''):
    self.filename = filename

    if filename:
        self.setFile(filename)
    else:
        # initialize our attributes to None
        for field in self.fileheader_fields:
            setattr(self,field,None) 
    def setFile(self, f):
    self.infile=open(f, 'rb')
    dtype=dict(names=self.fileheader_fields, formats=self.fileheader_formats)
    self.fileheader=np.fromfile(self.infile, dtype=dtype, count=1)
    self.fileheader_length=self.infile.tell()

    for field in self.fileheader_fields:
        setattr(self,field,self.fileheader[field])        

我已经使用此代码填充表格,但我不断收到“FileHeader没有属性fileheader”错误。

from fileheader import FileHeader, Frame
from echogram import QEchogram
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import os, sys


class MainWindow(QWidget):

    def __init__(self, parent=None):
        self.fileheader_fields=FileHeader.fileheader_fields
        self.fileheader_values=FileHeader.fileheader[field]
        self.fileheader={field: "value of" + field
                         for field in self.fileheader_fields}
        super(MainWindow, self).__init__(parent)
        self.fileheader_table=QTableWidget()
        layout=QVBoxLayout()
        layout.addWidget(self.fileheader_table)
        self.setLayout(layout)
        self.populate

    def populate(self):
        self.fileheader_table.setRowCount(len(self.fileheader_fields))
        self.fileheader_table.sestColumnCount(2)
        self.fileheader_table.setHorizontalHeaderLabels(['name','value'])
        for i,field in enumerate(self.fileheader_fields):
            name=QTableWidgetItem(field)
            value=QTableWidgetItem(self.fileheader[field])
            self.fileheader_table.setItem(i,0,name)
            self.fileheader_table.setItem(i,1,value)

    if __name__=="__main__":
        app=QApplication(sys.argv)
        filename=str(QFileDialog.getOpenFileName(None,"open  file","C:/vprice/DIDSON/DIDSON  Data","*.ddf"))
        wnd=MainWindow()
        wnd.resize(640,480)
        wnd.show()
        #echoGram=QEchogram()
        #echoGram.initFromFile(filename)
        #fileName="test.png"
        #echoGram.processEchogram()
        #dataH=echoGram.data
        #print "Horizontal data", dataH

忍受我 - 一个月前我刚开始使用所有Python的东西......

2 个答案:

答案 0 :(得分:3)

请参阅populate方法。 documentation

中也有一些例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui


class MainWindow(QtGui.QWidget):

    def __init__(self, parent=None):

        self.fileheader_fields=(
            "filetype","fileversion","numframes",
            "framerate","resolution","numbeams",
            "samplerate","samplesperchannel","receivergain",
            "windowstart","winlengthsindex","reverse",
            "serialnumber","date","idstring","ID1","ID2",
            "ID3","ID4","framestart","frameend","timelapse",
            "recordInterval","radioseconds","frameinterval","userassigned"
        )
        # just for test
        self.fileheader = {field: 'value of ' + field 
                           for field in self.fileheader_fields}
        super(MainWindow, self).__init__(parent)
        self.table_widget = QtGui.QTableWidget()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.table_widget)
        self.setLayout(layout)
        self.populate()

    def populate(self):
        self.table_widget.setRowCount(len(self.fileheader_fields))
        self.table_widget.setColumnCount(2)
        self.table_widget.setHorizontalHeaderLabels(['name', 'value'])
        for i, field in enumerate(self.fileheader_fields):
            name = QtGui.QTableWidgetItem(field)
            value = QtGui.QTableWidgetItem(self.fileheader[field])
            self.table_widget.setItem(i, 0, name)
            self.table_widget.setItem(i, 1, value)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    wnd = MainWindow()
    wnd.resize(640, 480)
    wnd.show()
    sys.exit(app.exec_())

UPD

具体案例的代码:

from fileheader import FileHeader, Frame
from echogram import QEchogram
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import os, sys


class MainWindow(QWidget):

    def __init__(self, filename, parent=None):
        super(MainWindow, self).__init__(parent)
        # here we are loading file
        # now self.fileheader contains attributes
        self.fileheader = FileHeader(filename)
        self.fileheader_table = QTableWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.fileheader_table)
        self.setLayout(layout)
        self.populate()

    def populate(self):
        self.fileheader_table.setRowCount(len(self.fileheader.fileheader_fields))
        self.fileheader_table.sestColumnCount(2)
        self.fileheader_table.setHorizontalHeaderLabels(['name','value'])
        for i,field in enumerate(self.fileheader.fileheader_fields):
            name=QTableWidgetItem(field)
            value=QTableWidgetItem(getattr(self.fileheader, field))
            self.fileheader_table.setItem(i,0,name)
            self.fileheader_table.setItem(i,1,value)

    if __name__=="__main__":
        app=QApplication(sys.argv)
        filename=str(QFileDialog.getOpenFileName(None,"open  file","C:/vprice/DIDSON/DIDSON  Data","*.ddf"))
        wnd=MainWindow(filename)
        wnd.resize(640,480)
        wnd.show()
        #echoGram=QEchogram()
        #echoGram.initFromFile(filename)
        #fileName="test.png"
        #echoGram.processEchogram()
        #dataH=echoGram.data
        #print "Horizontal data", dataH

答案 1 :(得分:0)

好的,你必须在你的自定义QtGui.QMainWindow中添加一个QTableWidget 我会创建我的第0行和正确数量的柱子,如下所示:

self.tableArea=QtGui.QTableWidget(0,self.fileheader_length,self)
self.setHorizontalHeaderLabels(['nameOne','nameTwo'])#will name your top header

self.verticalHeader().setVisible(False)#will hide your left header if you don't need them

并逐个添加您的行 self.tableArea.insertRow(row)#it将在行位置添加一行

之后你必须为每个单元格创建一个QTableWidgetItem

 itemTo=QtGui.QTableWidgetItem('text')#replace text by your value

并将您的项目放在所需的单元格中

 self.tableArea.setItem(row, column, itemTo)