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 -------------------------------------------------------- -
from PyQt4 import QtGui, QtCore
-
from tstMain import Ui_tstMain
-
-
import sys, string
-
from os.path import isfile
-
from os import chdir
-
-
import variousFuncs
-
-
-
## Create a dictionary of updateable variables. These will be updated by the various
-
## functions of Class startGui
-
updVars = {"InitialFile": [], "SelectedColumns": []}
-
-
## the Ui_tstMain module is imported and is a file generated by pyuic4, out of
-
## a "layout" file tstMain.ui created by Qt4
-
class startGui(QtGui.QMainWindow):
-
def __init__(self, parent = None):
-
QtGui.QWidget.__init__(self, parent)
-
self.ui = Ui_tstMain()
-
self.ui.setupUi(self)
-
-
## create our slots here
-
QtCore.QObject.connect(self.ui.btn_SetWorkingDir, QtCore.SIGNAL("clicked()"), self.setWorkingDir)
-
QtCore.QObject.connect(self.ui.btn_OpenFile, QtCore.SIGNAL("clicked()"), self.openFile)
-
QtCore.QObject.connect(self.ui.btn_ListShow, QtCore.SIGNAL("clicked()"), self.showList)
-
-
def setWorkingDir(self):
-
wd = QtGui.QFileDialog(self)
-
currentDir = QtCore.QString(wd.getExistingDirectory())
-
self.ui.lnEdt_WorkingDir.setText(currentDir)
-
chdir(currentDir)
-
-
def openFile(self):
-
fd = QtGui.QFileDialog(self)
-
self.file = fd.getOpenFileName()
-
-
if isfile(self.file):
-
fileToOpen = open(self.file)
-
initialFile = [string.split(line) for line in fileToOpen]
-
variousFuncs.dbl_str2num(initialFile)
-
-
updVars["InitialFile"] = initialFile
-
variousFuncs.tablePainter(initialFile, self.ui.tbl_OpenFile)
-
-
updVars["SelectedColumns"] = self.ui.tbl_OpenFile.selectedItems
-
-
def showList(self):
-
tempSelected = updVars["SelectedColumns"]
-
variousFuncs.tablePainter(tempSelected, self.ui.tbl_ListShow)
-
-
if __name__ == "__main__":
-
app = QtGui.QApplication(sys.argv)
-
appStart = startGui()
-
appStart.show()
-
sys.exit(app.exec_())
--------------------------------------code end--------------------------------------------------------------
the various function script is this:
varousFuncs.py:
-----------------------------------code start -------------------------------------------------------- -
#!/usr/bin/python
-
-
import string, random, math
-
from PyQt4 import QtGui, QtCore
-
-
##
-
def dbl_str2num(lst):
-
""" This function transforms the items of the list "lst" from strings to numbers.
-
The list must be a nested list. """
-
for i in range(len(lst)):
-
for j in range(len(lst[0])):
-
lst[i][j] = eval(lst[i][j])
-
-
def tablePainter(someTwoDimLst, someTbl):
-
""" This function creates a QTableWidgetItem out of a 2-dimension nested list which contains numbers,
-
and then uses it to "paint" the someTbl object, which is a QTableWidget """
-
someTbl.setColumnCount(len(someTwoDimLst[0]))
-
someTbl.setRowCount(len(someTwoDimLst))
-
-
for i in range(len(someTwoDimLst)):
-
for j in range(len(someTwoDimLst[0])):
-
itemListShow = QtGui.QTableWidgetItem(QtCore.QString.number(someTwoDimLst[i][j]), QtGui.QTableWidgetItem.Type)
-
someTbl.setItem(i, j, itemListShow)
--------------------------------------code end--------------------------------------------------------------
as shown, the critical line in main.py is the line: -
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
4 8018 bartonc 6,596
Recognized Expert Expert
Should be: - #
-
initialFile = [line.split() for line in fileToOpen.readlines()]
on line #40
Thank you bartonc for the suggestion. - initialFile = [line.split() for line in fileToOpen.readlines()]
works,
as well as my version: - 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: -
# -*- coding: utf-8 -*-
-
-
# Form implementation generated from reading ui file 'tstMain.ui'
-
#
-
# Created: Sun Sep 30 21:39:12 2007
-
# by: PyQt4 UI code generator 4.3
-
#
-
# WARNING! All changes made in this file will be lost!
-
-
from PyQt4 import QtCore, QtGui
-
-
class Ui_tstMain(object):
-
def setupUi(self, tstMain):
-
tstMain.setObjectName("tstMain")
-
tstMain.setEnabled(True)
-
tstMain.resize(QtCore.QSize(QtCore.QRect(0,0,951,394).size()).expandedTo(tstMain.minimumSizeHint()))
-
-
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Preferred)
-
sizePolicy.setHorizontalStretch(0)
-
sizePolicy.setVerticalStretch(0)
-
sizePolicy.setHeightForWidth(tstMain.sizePolicy().hasHeightForWidth())
-
tstMain.setSizePolicy(sizePolicy)
-
tstMain.setLayoutDirection(QtCore.Qt.LeftToRight)
-
-
self.centralwidget = QtGui.QWidget(tstMain)
-
self.centralwidget.setObjectName("centralwidget")
-
-
self.tbl_OpenFile = QtGui.QTableWidget(self.centralwidget)
-
self.tbl_OpenFile.setGeometry(QtCore.QRect(110,80,811,121))
-
-
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
-
sizePolicy.setHorizontalStretch(0)
-
sizePolicy.setVerticalStretch(0)
-
sizePolicy.setHeightForWidth(self.tbl_OpenFile.sizePolicy().hasHeightForWidth())
-
self.tbl_OpenFile.setSizePolicy(sizePolicy)
-
self.tbl_OpenFile.setMaximumSize(QtCore.QSize(16777215,16777215))
-
self.tbl_OpenFile.setLineWidth(1)
-
self.tbl_OpenFile.setObjectName("tbl_OpenFile")
-
-
self.btn_OpenFile = QtGui.QPushButton(self.centralwidget)
-
self.btn_OpenFile.setGeometry(QtCore.QRect(20,80,81,23))
-
self.btn_OpenFile.setObjectName("btn_OpenFile")
-
-
self.tbl_ListShow = QtGui.QTableWidget(self.centralwidget)
-
self.tbl_ListShow.setGeometry(QtCore.QRect(20,260,901,81))
-
self.tbl_ListShow.setObjectName("tbl_ListShow")
-
-
self.btn_SetWorkingDir = QtGui.QPushButton(self.centralwidget)
-
self.btn_SetWorkingDir.setGeometry(QtCore.QRect(20,50,82,23))
-
self.btn_SetWorkingDir.setObjectName("btn_SetWorkingDir")
-
-
self.lnEdt_WorkingDir = QtGui.QLineEdit(self.centralwidget)
-
self.lnEdt_WorkingDir.setEnabled(True)
-
self.lnEdt_WorkingDir.setGeometry(QtCore.QRect(110,50,811,20))
-
self.lnEdt_WorkingDir.setAutoFillBackground(False)
-
self.lnEdt_WorkingDir.setReadOnly(True)
-
self.lnEdt_WorkingDir.setObjectName("lnEdt_WorkingDir")
-
-
self.btn_ListShow = QtGui.QPushButton(self.centralwidget)
-
self.btn_ListShow.setGeometry(QtCore.QRect(730,230,191,23))
-
self.btn_ListShow.setObjectName("btn_ListShow")
-
tstMain.setCentralWidget(self.centralwidget)
-
-
self.menubar = QtGui.QMenuBar(tstMain)
-
self.menubar.setGeometry(QtCore.QRect(0,0,951,21))
-
self.menubar.setObjectName("menubar")
-
tstMain.setMenuBar(self.menubar)
-
-
self.statusbar = QtGui.QStatusBar(tstMain)
-
self.statusbar.setObjectName("statusbar")
-
tstMain.setStatusBar(self.statusbar)
-
-
self.retranslateUi(tstMain)
-
QtCore.QMetaObject.connectSlotsByName(tstMain)
-
-
def retranslateUi(self, tstMain):
-
tstMain.setWindowTitle(QtGui.QApplication.translate("tstMain", "My Test Application", None, QtGui.QApplication.UnicodeUTF8))
-
self.tbl_OpenFile.setRowCount(0)
-
self.tbl_OpenFile.clear()
-
self.tbl_OpenFile.setColumnCount(0)
-
self.tbl_OpenFile.setRowCount(0)
-
self.btn_OpenFile.setText(QtGui.QApplication.translate("tstMain", "Open File", None, QtGui.QApplication.UnicodeUTF8))
-
self.tbl_ListShow.clear()
-
self.tbl_ListShow.setColumnCount(0)
-
self.tbl_ListShow.setRowCount(0)
-
self.btn_SetWorkingDir.setText(QtGui.QApplication.translate("tstMain", "Set Working Dir", None, QtGui.QApplication.UnicodeUTF8))
-
self.lnEdt_WorkingDir.setText(QtGui.QApplication.translate("tstMain", "Working Directory NOT yet set !", None, QtGui.QApplication.UnicodeUTF8))
-
self.btn_ListShow.setText(QtGui.QApplication.translate("tstMain", "Show List", None, QtGui.QApplication.UnicodeUTF8))
-
-
Thomas
bartonc 6,596
Recognized Expert Expert
Thank you bartonc for the suggestion. - initialFile = [line.split() for line in fileToOpen.readlines()]
works,
as well as my version: - 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.
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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
|
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?
|
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...
|
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'...
| |
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
|
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 " &
|
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?
|
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
|
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...
|
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,...
| |
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...
|
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,...
|
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...
|
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();...
|
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...
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |