Results 1 to 11 of 11

Thread: Select columns from a QTableWidget

  1. #1
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Select columns from a QTableWidget

    Hi to all !!!

    I'm new here and a newbie at the same time, so please don't be harsh...

    I use Python with PyQt4 to develop a program reading a file with numbers and displaying them in a QTableWidget. So far so good.

    What I have not accomplished yet, is to select certain columns from the QTableWidget and display them in another table. I would also like to store the selected tables' indexes in a global list.

    My main.py file, the one that materializes the GUI and uses the derivative file from pyuic4 looks something like this:

    Qt Code:
    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. class startGui(QtGui.QMainWindow):
    16. def __init__(self, parent = None):
    17. QtGui.QWidget.__init__(self, parent)
    18. self.ui = Ui_tstMain()
    19. self.ui.setupUi(self)
    20.  
    21. ## create our slots here
    22. QtCore.QObject.connect(self.ui.btn_SetWorkingDir, QtCore.SIGNAL("clicked()"), self.setWorkingDir)
    23. QtCore.QObject.connect(self.ui.btn_OpenFile, QtCore.SIGNAL("clicked()"), self.openFile)
    24. QtCore.QObject.connect(self.ui.btn_ListShow, QtCore.SIGNAL("clicked()"), self.showList)
    25.  
    26. def setWorkingDir(self):
    27. wd = QtGui.QFileDialog(self)
    28. currentDir = QtCore.QString(wd.getExistingDirectory())
    29. self.ui.lnEdt_WorkingDir.setText(currentDir)
    30. chdir(currentDir)
    31.  
    32. def openFile(self):
    33. fd = QtGui.QFileDialog(self)
    34. self.file = fd.getOpenFileName()
    35.  
    36. if isfile(self.file):
    37. fileToOpen = open(self.file)
    38. initialFile = [line.split() for line in fileToOpen.readlines()]
    39. variousFuncs.dbl_str2num(initialFile)
    40.  
    41. updVars["InitialFile"] = initialFile
    42. variousFuncs.tablePainter(initialFile, self.ui.tbl_OpenFile)
    43.  
    44. updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems()
    45.  
    46. def showList(self):
    47. tempSelected = updVars["SelectedColumns"]
    48. variousFuncs.tablePainter(tempSelected, self.ui.tbl_ListShow)
    To copy to clipboard, switch view to plain text mode 

    while the variousFuncs file which contains various functions, looks something like this:

    Qt Code:
    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)
    To copy to clipboard, switch view to plain text mode 

    currently, when I select certain columns from the tbl_OpenFile QTableWidget and try to display them in the tbl_ListShow one, the whole thing ends up with the error:
    Qt Code:
    1. Traceback (most recent call last):
    2. File "D:\Tutorial\main.py", line 52, in showList
    3. itemListShow = QtGui.QTableWidgetItem(QtCore.QString.number(tempSelected[0][0]))
    4. IndexError: list index out of range
    To copy to clipboard, switch view to plain text mode 

    which IMHO means that the line

    Qt Code:
    1. updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems()
    To copy to clipboard, switch view to plain text mode 
    returned nothing in the list (???)

    Any help would be much appreciated.
    Thank you all in advance,

    Thomas

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 975 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Select columns from a QTableWidget

    Quote Originally Posted by toglez View Post
    currently, when I select certain columns from the tbl_OpenFile QTableWidget and try to display them in the tbl_ListShow one, the whole thing ends up with the error
    Do these "certain columns" happen to be empty?

  3. #3
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    OK - now I forgot to also post the derivative file of the pyuic4. After I had designed the layout with QT Designer, I created the following tstMain.py file via pyuic4:

    Qt Code:
    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))
    To copy to clipboard, switch view to plain text mode 

    OK - Once I run the main.py file I am presented with the option to load a file in the first QTableWidget and I do so. In this way, the first QTableWidget named tbl_OpenFile is full of numbers imported from the opened file.
    I then try to select whole columns here and there clicking with the mouse on the headers of the table. And so it does - the columns are selected...

    ...but when I click on the button btn_ListShow responsible to transfer my selection to the last QTable Widget named tbl_ListShow, I get the aforementioned error.

    Thanx again,
    Thomas

  4. #4
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 975 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Select columns from a QTableWidget

    Quote Originally Posted by toglez View Post
    I am presented with the option to load a file in the first QTableWidget and I do so. [...] I then try to select whole columns here and there clicking with the mouse on the headers of the table. [...] but when I click on the button btn_ListShow responsible to transfer my selection to the last QTable Widget named tbl_ListShow, I get the aforementioned error.
    You retrieve the selected items in openFile(). Isn't that before you have a chance to select anything?

    P.S. Unfortunately I can't test your code, because PyQt4 package I have is for some reason incompatible with Qt4 installed on my system. I've tried to build PyQt4 from source, but GCC didn't survive this (probably because of OOM error).

  5. #5
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    The line responsible to collect the selected lines is line 44 in main.py:

    Qt Code:
    1. updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems()
    To copy to clipboard, switch view to plain text mode 

    This is of course inside the function openFile(). This line instructs the program to update the global dictionary {updVars} in its element "SelectedColumns" (which is a Python list) with any - if any - selected columns of the table tbl_OpenFile. At least, that was my intention.

    The problem is that after some tests* I have conducted, it is proved that the global dictionary is not updated and the element list "SelectedColumns" is empty, that's why the program ends with this error.

    So, either the columns are not actually selected with a simple mouse click, or the code is not written that way.

    Thomas.

    *test: after instructing the program to return the length of the global list "SelectedItems", it returns 0, no matter what column selection has been done on the table.

  6. #6
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    5,372
    Thanks
    28
    Thanked 975 Times in 912 Posts
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Select columns from a QTableWidget

    Quote Originally Posted by toglez View Post
    This is of course inside the function openFile(). This line instructs the program to update the global dictionary {updVars} in its element "SelectedColumns" (which is a Python list) with any - if any - selected columns of the table tbl_OpenFile.
    As you wrote earlier, you first invoke openFile(), then you select columns and finally you call showList(). The problem is that you check what columns were selected in openFile(), that is before you select them. Move that line to showList() and it should work.

    Do you really need that global dictionary?

  7. The following user says thank you to jacek for this useful post:

    toglez (7th October 2007)

  8. #7
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    et voila!!! It worked !!!

    Thank you jacek, I really owe you one!

    Problem solved.

    The global dictionary is needed so as to put there various updates of the various variables, because the project is a much more complicated program, needing to display various pieces of information from various sources. (At least I think I need it...)

    Thank you again.

    Thomas

  9. #8
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    Now would someone be so very kind as to show me how I am to collect the indexes of the selected columns of the table (e.g. 0, 1, 5, etc)?

    Thanx again in advance

    Thomas

  10. #9
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    Anybody any ideas?

    Thomas

  11. #10
    Join Date
    Feb 2006
    Location
    Oslo, Norway
    Posts
    6,264
    Thanks
    36
    Thanked 1,518 Times in 1,388 Posts
    Qt products
    Qt4
    Platforms
    MacOS X Unix/X11 Windows Symbian S60 Maemo/MeeGo

    Default Re: Select columns from a QTableWidget

    Take a look at QItemSelectionModel which is accessible via QAbstractItemView.selectionModel.
    J-P Nurmi

  12. The following user says thank you to jpn for this useful post:

    toglez (7th October 2007)

  13. #11
    Join Date
    Oct 2007
    Posts
    7
    Thanks
    2

    Default Re: Select columns from a QTableWidget

    I think I have eventually come up with a solution.

    It seems that each selected item has an attribute column() (or row() of course), which returns the item's column (or row) as an integer. So, if I would like to test the existence of selected columns it would now be rather easy to isolate them:

    Qt Code:
    1. def showList(self):
    2. tempSelected = self.ui.tbl_OpenFile.selectedItems()
    3.  
    4. tempLst = []
    5.  
    6. for i in tempSelected:
    7. if i.row() == 0: tempLst.append(i.column())
    8.  
    9. tempLst.sort()
    10.  
    11. s = ""
    12.  
    13. for i in xrange(len(tempLst)):
    14. s += str(tempLst[i]) + " "
    15.  
    16. self.ui.txtEd_ListShow.setText(QtCore.QString(s))
    To copy to clipboard, switch view to plain text mode 

    The above function gathers the selected items' list in a locally defined list named tempSelected. Then, for each member of this list the function adds the corresponding column to a string, which then displays in a text edit window by the name txtEd_ListShow.

    Thomas

Similar Threads

  1. QTableWidget - images in columns
    By bruccutler in forum Qt Programming
    Replies: 3
    Last Post: 1st May 2007, 19:28
  2. QTableWidget columns to expand to window size
    By bruccutler in forum Newbie
    Replies: 1
    Last Post: 13th April 2007, 17:02
  3. Select None in QTableWidget
    By Rayven in forum Qt Programming
    Replies: 2
    Last Post: 9th June 2006, 15:10
  4. Maximize columns on QTableWidget
    By marcelrc in forum Newbie
    Replies: 1
    Last Post: 21st May 2006, 16:34
  5. Replies: 6
    Last Post: 5th March 2006, 22:05

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.