How do I insert data from file in the first column of a qtablewidget or qtableview?

2k views Asked by At

I would like to insert a list of users from a file into the first row of a tablewidget or tableview. I am currently trying it out with a tablewidget. So far, the code below is what I came up with after having seen the answer from this post. Basically if you look at the image, I'm trying to do exactly that then later I'll add an ok button to perform the actions.

todo

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        self.table.setHorizontalHeaderItem(0, QtGui.QTableWidgetItem("Users"))
        self.table.setHorizontalHeaderItem(1, QtGui.QTableWidgetItem("Delete User"))
        self.table.setHorizontalHeaderItem(2, QtGui.QTableWidgetItem("Delete User and Home"))
        self.table.verticalHeader().hide()
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)
        for column in range(columns):
            if column == 0:
                with open("users") as input:
                    if input is not None:
                        users = input.readlines()
                    for line in users:
                        users = QtGui.QTableWidgetItem(line)
                        print line
                    input.close()
            for row in range(rows):
                if column % 3:
                    item = QtGui.QTableWidgetItem('%d' % column)
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                    item.setCheckState(QtCore.Qt.Unchecked)
                    self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.resize(400, 400)
    window.show()
    sys.exit(app.exec_())
2

There are 2 answers

2
Subin Gopi On BEST ANSWER
#How do I insert data from file in the first column of a qtablewidget or qtableview?

#This is the example code for insert data to Qtablewidget
#Please not the print result. I hope you can understand how to use columns and row values.
#I used the input data from "dictionary variable - self.input". You can replace this input variable to your input data.
#if any doubts regarding this below code, please let me know.
#If your are not expecting this answer, sorry.
#Thanks, Subin

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class Window (QtGui.QWidget):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        #Read user text file and append to dictionary variable         
        userDataPath        = 'C:/Users/Subin/Desktop/userList.txt'                
        readUserData        = open (userDataPath, 'r')        
        userList            = readUserData.readlines ()        
        #self.input          = {'bruno':[0,1], 'shelly':[0,0], 'nobody':[1,1]}        
        self.input          = {}

        for eachUser in userList :
            if eachUser.strip() :
                self.input.setdefault (eachUser.strip(), [1, 1])              

        self.rows           = 3
        self.columns        = len(self.input)        

        self.tableWidget    = QtGui.QTableWidget (self)           
        self.tableWidget.setGeometry (QtCore.QRect(10, 10, 500, 180))
        self.tableWidget.setObjectName ('tableWidget')
        self.tableWidget.setColumnCount(self.rows)
        self.tableWidget.setRowCount(self.columns)        

        print '\t\tcolumns rows\n'         
        cLoop       = 0
        for eachInput in self.input :        
            self.item_name       = QtGui.QTableWidgetItem ()
            self.tableWidget.setItem (cLoop, 0, self.item_name)
            self.item_name.setText (eachInput)               
            print 'name\t\tcolumns ',  cLoop, ' rows ', 0   

            rLoop   = 0
            for eachAttri in self.input[eachInput] :                
                self.item_attri       = QtGui.QTableWidgetItem ()                
                self.tableWidget.setItem (cLoop, rLoop+1, self.item_attri)                                
                self.item_attri.setFlags (QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)  

                self.item_attri.setCheckState (QtCore.Qt.Unchecked)                                
                if eachAttri==1 :
                    self.item_attri.setCheckState (QtCore.Qt.Checked)                
                print 'attributes\tcolumns ',  cLoop, ' rows ', rLoop+1                
                rLoop+=1

            cLoop+=1                
            print '\n'        

if __name__=='__main__':
    app     = QtGui.QApplication(sys.argv)
    wind = Window ()
    wind.show()
    sys.exit(app.exec_())
3
ImportanceOfBeingErnest On

The following code may do what you need. It assumes that you have a file users.txt, which consists of one name per row, like

Harry
Sally
Wang
Jon
Leona

You then need to read that file and get rid of the line break character.

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        with open("users.txt") as f:
            users = f.readlines()
            users = [user.split("\n")[0] for user in users]

        self.table = QtGui.QTableWidget(len(users), 2, self)
        self.table.setHorizontalHeaderLabels(["Delete User", "Delete Home"])
        self.table.setVerticalHeaderLabels(users)
        for column in range(2):
            for row in range(len(users)):
                item = QtGui.QTableWidgetItem("")
                item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                item.setCheckState(QtCore.Qt.Unchecked)
                self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())