473,657 Members | 2,753 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Select columns from a QTableWidget

3 New Member
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\ma in.py", line 48, in showList
variousFuncs.ta blePainter(temp Selected, self.ui.tbl_Lis tShow)
File "D:\Tutorial\va riousFuncs.py", line 17, in tablePainter
someTbl.setColu mnCount(len(som eTwoDimLst[0]))
TypeError: unsubscriptable object

Any help would be much appreciated
Thanx all in advance,

Thomas
Oct 3 '07 #1
4 8018
bartonc
6,596 Recognized Expert Expert
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 New Member
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 Recognized Expert Expert
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\ma in.py", line 48, in showList
variousFuncs.ta blePainter(temp Selected, self.ui.tbl_Lis tShow)
File "D:\Tutorial\va riousFuncs.py", line 17, in tablePainter
someTbl.setColu mnCount(len(som eTwoDimLst[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 New Member
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
15684
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 like to create a dynamically-generated SELECT--limiting the columns to only those that are populated. If, for example, only columns COL1, COL8, and COL93 are populated for this one record in the MYTEST table, the generated SELECT statement would...
9
1726
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, q3, q4, q5, q6, q7, q8, q9 FROM exam
2
1656
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 SPEED) but I don't know if it has something to do with the use of select. Waht can I use instead?
3
6449
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 COULD be wrong... :) I've tried the access group...twice...and all I get is "Access doesn't like ".", which I know, or that my query names are too long, as there's a limit to the length of the SQL statement(s). But this works when I don't try to...
8
7249
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 same number of columns, how ever they don't. I only need the first 5 columns from each the table, in the case where they have more than the 5 i need for my 'Users' table i get this error: 'An explicit value for the identity column in table 'Users'...
3
1639
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 C# I have a datagrid that is bound to a datasource (through ADO.net) and all that works
4
1653
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 The select is: Dim da2 As New OleDb.OleDbDataAdapter("Select * from " &
2
2898
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 Visible property on the columns it causes the underlying ObjectDataSource to re-issue the Select statement. How can I hide these columns without double clutching the ODS Select?
1
3677
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 clipboard. Come posso risolvere il problema? Grazie in anticipo
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8498
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5629
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.