473,378 Members | 1,592 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Select columns from a QTableWidget

3
Hi all!

I use PyQt4 and Python to create a program to display numbers from a file in a QTable Widget, select various columns from the table and then display the selected columns in a new table.

Well, I don't seem to understand how to do this. Here is my code:

main.py:
-------------
-----------------------------------code start --------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1. from PyQt4 import QtGui, QtCore
  2. from tstMain import Ui_tstMain
  3.  
  4. import sys, string
  5. from os.path import isfile
  6. from os import chdir
  7.  
  8. import variousFuncs
  9.  
  10.  
  11. ## Create a dictionary of updateable variables. These will be updated by the various
  12. ## functions of Class startGui
  13. updVars = {"InitialFile": [], "SelectedColumns": []}
  14.  
  15. ## the Ui_tstMain module is imported and is a file generated by pyuic4, out of
  16. ## a "layout" file tstMain.ui created by Qt4
  17. class startGui(QtGui.QMainWindow):
  18.     def __init__(self, parent = None):
  19.         QtGui.QWidget.__init__(self, parent)
  20.         self.ui = Ui_tstMain()
  21.         self.ui.setupUi(self)
  22.  
  23.         ## create our slots here
  24.         QtCore.QObject.connect(self.ui.btn_SetWorkingDir, QtCore.SIGNAL("clicked()"), self.setWorkingDir)
  25.         QtCore.QObject.connect(self.ui.btn_OpenFile, QtCore.SIGNAL("clicked()"), self.openFile)
  26.         QtCore.QObject.connect(self.ui.btn_ListShow, QtCore.SIGNAL("clicked()"), self.showList)
  27.  
  28.     def setWorkingDir(self):
  29.         wd = QtGui.QFileDialog(self)
  30.         currentDir = QtCore.QString(wd.getExistingDirectory())
  31.         self.ui.lnEdt_WorkingDir.setText(currentDir)
  32.         chdir(currentDir)
  33.  
  34.     def openFile(self):
  35.         fd = QtGui.QFileDialog(self)
  36.         self.file = fd.getOpenFileName()
  37.  
  38.         if isfile(self.file):
  39.             fileToOpen = open(self.file)
  40.             initialFile = [string.split(line) for line in fileToOpen]
  41.             variousFuncs.dbl_str2num(initialFile)
  42.  
  43.             updVars["InitialFile"] = initialFile
  44.             variousFuncs.tablePainter(initialFile, self.ui.tbl_OpenFile)
  45.  
  46.             updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems
  47.  
  48.     def showList(self):
  49.         tempSelected = updVars["SelectedColumns"]
  50.         variousFuncs.tablePainter(tempSelected, self.ui.tbl_ListShow)
  51.  
  52. if __name__ == "__main__":
  53.     app = QtGui.QApplication(sys.argv)
  54.     appStart = startGui()
  55.     appStart.show()
  56.     sys.exit(app.exec_())
--------------------------------------code end--------------------------------------------------------------

the various function script is this:
varousFuncs.py:
-----------------------------------code start --------------------------------------------------------
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2.  
  3. import string, random, math
  4. from PyQt4 import QtGui, QtCore
  5.  
  6. ##
  7. def dbl_str2num(lst):
  8.     """ This function transforms the items of the list "lst" from strings to numbers.
  9.     The list must be a nested list. """
  10.     for i in range(len(lst)):
  11.         for j in range(len(lst[0])):
  12.             lst[i][j] = eval(lst[i][j])
  13.  
  14. def tablePainter(someTwoDimLst, someTbl):
  15.     """ This function creates a QTableWidgetItem out of a 2-dimension nested list which contains numbers,
  16.     and then uses it to "paint" the someTbl object, which is a QTableWidget """
  17.     someTbl.setColumnCount(len(someTwoDimLst[0]))
  18.     someTbl.setRowCount(len(someTwoDimLst))
  19.  
  20.     for i in range(len(someTwoDimLst)):
  21.         for j in range(len(someTwoDimLst[0])):
  22.             itemListShow = QtGui.QTableWidgetItem(QtCore.QString.number(someTwoDimLst[i][j]), QtGui.QTableWidgetItem.Type)
  23.             someTbl.setItem(i, j, itemListShow)
--------------------------------------code end--------------------------------------------------------------

as shown, the critical line in main.py is the line:
Expand|Select|Wrap|Line Numbers
  1. updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems
which updates the global dictionary updVars with the selected columns (does it???) from the table tbl_OpenFile. The dictionary data is then used by the function showList() to display the selected items in a new table.

The whole thing ends up with the following error error:

Traceback (most recent call last):
File "D:\Tutorial\main.py", line 48, in showList
variousFuncs.tablePainter(tempSelected, self.ui.tbl_ListShow)
File "D:\Tutorial\variousFuncs.py", line 17, in tablePainter
someTbl.setColumnCount(len(someTwoDimLst[0]))
TypeError: unsubscriptable object

Any help would be much appreciated
Thanx all in advance,

Thomas
Oct 3 '07 #1
4 7994
bartonc
6,596 Expert 4TB
Should be:
Expand|Select|Wrap|Line Numbers
  1. #
  2.             initialFile = [line.split() for line in fileToOpen.readlines()]
on line #40
Oct 3 '07 #2
toglez
3
Thank you bartonc for the suggestion.

Expand|Select|Wrap|Line Numbers
  1. initialFile = [line.split() for line in fileToOpen.readlines()]
works,
as well as my version:
Expand|Select|Wrap|Line Numbers
  1. initialFile = [string.split(line) for line in fileToOpen]
but this doesn't cure the problem. I am still not able to select the columns and display them into another table.

I also forgot to mention the python script (tstMain.py) created by pyuic4 out of the initial tstMain.ui file. So, this is it:

Expand|Select|Wrap|Line Numbers
  1. # -*- coding: utf-8 -*-
  2.  
  3. # Form implementation generated from reading ui file 'tstMain.ui'
  4. #
  5. # Created: Sun Sep 30 21:39:12 2007
  6. #      by: PyQt4 UI code generator 4.3
  7. #
  8. # WARNING! All changes made in this file will be lost!
  9.  
  10. from PyQt4 import QtCore, QtGui
  11.  
  12. class Ui_tstMain(object):
  13.     def setupUi(self, tstMain):
  14.         tstMain.setObjectName("tstMain")
  15.         tstMain.setEnabled(True)
  16.         tstMain.resize(QtCore.QSize(QtCore.QRect(0,0,951,394).size()).expandedTo(tstMain.minimumSizeHint()))
  17.  
  18.         sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Preferred)
  19.         sizePolicy.setHorizontalStretch(0)
  20.         sizePolicy.setVerticalStretch(0)
  21.         sizePolicy.setHeightForWidth(tstMain.sizePolicy().hasHeightForWidth())
  22.         tstMain.setSizePolicy(sizePolicy)
  23.         tstMain.setLayoutDirection(QtCore.Qt.LeftToRight)
  24.  
  25.         self.centralwidget = QtGui.QWidget(tstMain)
  26.         self.centralwidget.setObjectName("centralwidget")
  27.  
  28.         self.tbl_OpenFile = QtGui.QTableWidget(self.centralwidget)
  29.         self.tbl_OpenFile.setGeometry(QtCore.QRect(110,80,811,121))
  30.  
  31.         sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
  32.         sizePolicy.setHorizontalStretch(0)
  33.         sizePolicy.setVerticalStretch(0)
  34.         sizePolicy.setHeightForWidth(self.tbl_OpenFile.sizePolicy().hasHeightForWidth())
  35.         self.tbl_OpenFile.setSizePolicy(sizePolicy)
  36.         self.tbl_OpenFile.setMaximumSize(QtCore.QSize(16777215,16777215))
  37.         self.tbl_OpenFile.setLineWidth(1)
  38.         self.tbl_OpenFile.setObjectName("tbl_OpenFile")
  39.  
  40.         self.btn_OpenFile = QtGui.QPushButton(self.centralwidget)
  41.         self.btn_OpenFile.setGeometry(QtCore.QRect(20,80,81,23))
  42.         self.btn_OpenFile.setObjectName("btn_OpenFile")
  43.  
  44.         self.tbl_ListShow = QtGui.QTableWidget(self.centralwidget)
  45.         self.tbl_ListShow.setGeometry(QtCore.QRect(20,260,901,81))
  46.         self.tbl_ListShow.setObjectName("tbl_ListShow")
  47.  
  48.         self.btn_SetWorkingDir = QtGui.QPushButton(self.centralwidget)
  49.         self.btn_SetWorkingDir.setGeometry(QtCore.QRect(20,50,82,23))
  50.         self.btn_SetWorkingDir.setObjectName("btn_SetWorkingDir")
  51.  
  52.         self.lnEdt_WorkingDir = QtGui.QLineEdit(self.centralwidget)
  53.         self.lnEdt_WorkingDir.setEnabled(True)
  54.         self.lnEdt_WorkingDir.setGeometry(QtCore.QRect(110,50,811,20))
  55.         self.lnEdt_WorkingDir.setAutoFillBackground(False)
  56.         self.lnEdt_WorkingDir.setReadOnly(True)
  57.         self.lnEdt_WorkingDir.setObjectName("lnEdt_WorkingDir")
  58.  
  59.         self.btn_ListShow = QtGui.QPushButton(self.centralwidget)
  60.         self.btn_ListShow.setGeometry(QtCore.QRect(730,230,191,23))
  61.         self.btn_ListShow.setObjectName("btn_ListShow")
  62.         tstMain.setCentralWidget(self.centralwidget)
  63.  
  64.         self.menubar = QtGui.QMenuBar(tstMain)
  65.         self.menubar.setGeometry(QtCore.QRect(0,0,951,21))
  66.         self.menubar.setObjectName("menubar")
  67.         tstMain.setMenuBar(self.menubar)
  68.  
  69.         self.statusbar = QtGui.QStatusBar(tstMain)
  70.         self.statusbar.setObjectName("statusbar")
  71.         tstMain.setStatusBar(self.statusbar)
  72.  
  73.         self.retranslateUi(tstMain)
  74.         QtCore.QMetaObject.connectSlotsByName(tstMain)
  75.  
  76.     def retranslateUi(self, tstMain):
  77.         tstMain.setWindowTitle(QtGui.QApplication.translate("tstMain", "My Test Application", None, QtGui.QApplication.UnicodeUTF8))
  78.         self.tbl_OpenFile.setRowCount(0)
  79.         self.tbl_OpenFile.clear()
  80.         self.tbl_OpenFile.setColumnCount(0)
  81.         self.tbl_OpenFile.setRowCount(0)
  82.         self.btn_OpenFile.setText(QtGui.QApplication.translate("tstMain", "Open File", None, QtGui.QApplication.UnicodeUTF8))
  83.         self.tbl_ListShow.clear()
  84.         self.tbl_ListShow.setColumnCount(0)
  85.         self.tbl_ListShow.setRowCount(0)
  86.         self.btn_SetWorkingDir.setText(QtGui.QApplication.translate("tstMain", "Set Working Dir", None, QtGui.QApplication.UnicodeUTF8))
  87.         self.lnEdt_WorkingDir.setText(QtGui.QApplication.translate("tstMain", "Working Directory NOT yet set !", None, QtGui.QApplication.UnicodeUTF8))
  88.         self.btn_ListShow.setText(QtGui.QApplication.translate("tstMain", "Show List", None, QtGui.QApplication.UnicodeUTF8))
  89.  
  90.  
Thomas
Oct 3 '07 #3
bartonc
6,596 Expert 4TB
Thank you bartonc for the suggestion.

Expand|Select|Wrap|Line Numbers
  1. initialFile = [line.split() for line in fileToOpen.readlines()]
works,
as well as my version:
Expand|Select|Wrap|Line Numbers
  1. initialFile = [string.split(line) for line in fileToOpen]
but this doesn't cure the problem. I am still not able to select the columns and display them into another table.

Thomas
Yep, sorry to have missed that.
Traceback (most recent call last):
File "D:\Tutorial\main.py", line 48, in showList
variousFuncs.tablePainter(tempSelected, self.ui.tbl_ListShow)
File "D:\Tutorial\variousFuncs.py", line 17, in tablePainter
someTbl.setColumnCount(len(someTwoDimLst[0]))
TypeError: unsubscriptable object
Looking at it again, it seems to me that if there are no columns selected, then you well get this error, but I'm not familiar with QT.
Oct 3 '07 #4
toglez
3
But I do select columns during the runtime by clicking at the top of each one of them.

Thanx anyway, you are very kind...

Thomas.
Oct 3 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Tom Urbanowicz | last post by:
I have a table with 100+ columns, for which I'm trying to retrieve only 1 specific record. For this single record, I do not know which of the columns are NULL, and which are populated. I would...
9
by: Martin | last post by:
Hi there, I've been looking far and wide on this one. I'm looking for a way to select from columns where the columns have a certain pattern! Example: Instead of doing: SELECT q1, q2,...
2
by: bettina | last post by:
I read somewhere that to gain efficiency it is advisable to avoid the use of select. But they don't explain why or what to use instead. Is it true? I habe a problem of speed (better to say of NO...
3
by: Tcs | last post by:
My backend is DB2 on our AS/400. While I do HAVE DB2 PE for my PC, I haven't loaded it yet. I'm still using MS Access. And no, I don't believe this is an Access question. (But who knows? I...
8
by: carlospedr | last post by:
I have to insert data from about 30 tables into a single table (Users), to do so i used a cursor and a bit of dynamic sql, this should work fine if the tables have to do the select from had the...
3
by: CharlesA | last post by:
Hi folks, I really need help with the following scenario, I'm going to describe as well as a I can what the setup is and what I can't understand I'm using the framework 1.1 using ASP.net with...
4
by: tshad | last post by:
How do I tell DataAdapter that Column 2 and 3 are string and not integer? Following is the example data that comes from the .csv file FEDERAL TAX,1084,0000 COREHCR,1084,0000 CLIENT P,1084,0000...
2
by: =?Utf-8?B?SmF5IFBvbmR5?= | last post by:
Based on wether a row is selected in a GridView I need to HIDE the last two columns of a gridview. I do NOT need to make the cells invisible I want to hide the entire column. When I set the...
1
by: Antonio Valentino | last post by:
Ciao a tutti, ho un QTableWidget che ho reso non editabile settando editTriggers a NoEditTriggers. Il problema che adesso non posso selezionare una cela e copiarne il contenuto nella...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.