PDA

View Full Version : [Python] QTableWidget not displaying data when set as Main Window's central widget.



nice try
13th February 2012, 19:40
EDIT:
using PyQt 4.9.1 (32 bit) for Python 2.7 (32 bit) on Windows XP SP3 (32 bit), with Python 2.7 (32 bit).
/EDIT

Hello.

I am new to the forums and to PyQt. Generally speaking I am relatively new to programming as well.

I have a small app I am working on for the company I work for, but cannot make any progress until I get a breaking bug ironed out.

I have a MainWindow object and it has a QTextEdit widget set as an attribute and a QTableWidget set as an attribute. I have a function called initOpenDialog which does a check to see what type of file was opened. If the file is a .txt file, the TextEdit widget is set as the Main Window's central widget and the text is displayed within. If the file's type is .csv, the QTableWidget object is set as the Main Window's central widget, however, there are a couple different bugs when this happens.

Print statements are telling me that I am in fact receiving ALL the necessary data from these files to construct a QTableWidget with. When I set the central widget to this table widget, the app's central background color is changed from the default empty window color to the editor white color, however, there are no rows or columns displayed within the widget, and no data shows up.

Also, if any line of an opened text file exceeds the width of the QTextEdit widget, the widget is not even set as the main window's central widget at ALL.

Keep in mind this is still indev/temporary code and not all of the comments are 100% accurate to what some of the functions do here. Here's the full code to the program so far:


import sys, os, csv
from PyQt4 import QtGui
from PyQt4.Qt import *

class Spreadsheet(QTableWidget):
def __init__(self, *args):
super(Spreadsheet, self).__init__(*args)

def setData(self):
r = 0
for row in self.rows:
c = 0
for item in row:
i = QTableWidgetItem(item)
self.setItem(r, c, i)
c += 1
r += 1

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()

self.initUi()

def setTooltipFont(self, font, size):
QToolTip.setFont(QFont(str(font), int(size)))

def createAction(self, path, title, shortcut, tip, funct):
icon = QIcon(os.path.join(path))
action = QAction(icon, str(title), self)
action.setShortcut(str(shortcut))
action.setStatusTip(str(tip))
action.triggered.connect(funct)
return action

def getOpenDiologTip(self):
return 'Open an Excel Workbook or Worksheet in CSV format.'

def xls2csv(self, xls): pass

def initOpenDiolog(self):
fname = QFileDialog.getOpenFileName(
self, self.getOpenDiologTip(), '/home')

name, ext = os.path.splitext(str(fname))

with open(fname, 'r') as f:
editor = None
if ext == '.txt':
self.textEdit.setText(f.read())
editor = self.textEdit
elif ext == '.csv':
self.worksheetEdit.rows = list(csv.reader(f, 'excel'))
self.worksheetEdit.setData()
editor = self.worksheetEdit

self.setCentralWidget(editor)

def initFileMenu(self, menubar):
fileMenu = menubar.addMenu('&File')

fileMenu.addAction(self.createAction(
os.path.join('resources', 'icons', 'Open.ico'),
'Open', 'Ctrl+O', self.getOpenDiologTip(), self.initOpenDiolog))

fileMenu.addAction(self.createAction(
os.path.join('resources', 'icons', 'Exit.ico'),
'Quit', 'Ctrl+Q', 'Quit application.', self.close))

def getVersionInfo(self):
try:
with open('version_info.txt', 'r') as v:
split_lines = [line.split() for line in v.readlines()]
s = ''
for l, line in enumerate(split_lines):
s += makeString(split_lines[l])
if l < len(split_lines) - 1:
s += ', '
return s
except:
return '>>>>> ERROR <<<<< - Could not retrieve version info.'

def initUi(self):
menubar = self.menuBar()
statusbar = self.statusBar()

self.textEdit = QTextEdit()
self.worksheetEdit = Spreadsheet()

self.initFileMenu(menubar)

self.setGeometry(150, 150, 1024, 768)
self.setWindowTitle(self.getVersionInfo())
self.setWindowIcon(QIcon(os.path.join(
'resources', 'icons', 'logo.png')))

self.show()

def makeString(line):
""" Concatenates a single string using the given list of strings. """
s = ''
for w, word in enumerate(line):
W = word
if w == 0:
word += ' '
elif w == len(line) - 1:
word = ' ' + word
if len(line) == 1:
word = W
s += word
return s

def main():
app = QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())

if __name__ == '__main__':
main()


The code should work without version_info.txt or the resources directory.

Any help figuring this issue out would be greatly appreciated.

-Adam

norobro
13th February 2012, 22:04
You either need to construct your tableWidget large enough to hold all of your data or use QTableWidget::insertRow() and QTableWidget::insertColumn() in the loop where you add data. You can't set an item in a non-existent cell.

nice try
14th February 2012, 04:21
Ahh yes. Fixed it, ty =)

nice try
14th February 2012, 15:47
Edit:
Wow. upon two more seconds of inspecting the code I noticed that the row and column counts are passed to the widget for construction. My bad. Wow.

I also totally forgot about string.join()
/Edit

Actually, weird thought:

I found this example app that I used to create my table widget, however, this app doesn't set the column or row count but still displays the rows, columns and the data thereof... thought you might find it interesting. Can anybody explain why this works but my app didn't?


import sys
from PyQt4.Qt import *

lista = ['aa', 'ab', 'ac']
listb = ['ba', 'bb', 'bc']
listc = ['ca', 'cb', 'cc']
mystruct = {'A':lista, 'B':listb, 'C':listc}

class MyTable(QTableWidget):
def __init__(self, thestruct, *args):
QTableWidget.__init__(self, *args)
self.data = thestruct
self.setmydata()

def setmydata(self):
n = 0
for key in self.data:
m = 0
for item in self.data[key]:
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
m += 1
n += 1

def main(args):
app = QApplication(args)
table = MyTable(mystruct, 5, 3)
table.show()
sys.exit(app.exec_())

if __name__=="__main__":
main(sys.argv)