0

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_())
Community
  • 1
  • 1
answerSeeker
  • 2,692
  • 4
  • 38
  • 76
  • So what exactly is the problem? In how far does the code not do what you expect? – ImportanceOfBeingErnest Dec 17 '16 at 12:36
  • the `if column == 0:` block doesn't do what I expect it to do. – answerSeeker Dec 17 '16 at 17:53
  • (a) In your code you use the python word `input` as variable name. Never do that! (b) You loop over `users` and reassign `users` to be a `QTableWidgetItem` in that loop. After that `users` is never used again. So I don't know what you expect and you really need to be specific about your expectations. Write a statement like "I expect this code to....". – ImportanceOfBeingErnest Dec 17 '16 at 19:20

2 Answers2

1

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_())
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I haven't tried to debug it yet, your code compiles but doesn't run. – answerSeeker Dec 17 '16 at 18:15
  • What do you mean by "compiles but doesn't run"? Python code does not need to be compiled. It runs on my machine. Under the condition that you have a file named `users.txt` in the same directory, it should run for you as well. If you have problems running it, you need to be more specific about the issue. – ImportanceOfBeingErnest Dec 17 '16 at 19:13
  • My mistake, I ran it again and it works.I think that I haven't copied the `sys.exit(app.exec_())` the first time. I meant that It ran but nothing happened. I have a java background so I tried to explain it the way a java program would behave. Thanks for the help. – answerSeeker Dec 17 '16 at 19:21
1
#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_())
Subin Gopi
  • 541
  • 2
  • 12
  • This is exactly what I'd like to have but the users needs to come from a file. How could I translate `self.input` to a file where each lines of it contains a users? I'm sorry for so many questions but I am still a general beginner. – answerSeeker Dec 17 '16 at 18:24
  • I updated the previous code. Please check once. I hop this you expected. if any doubts regarding this code, please let me know. If your are not expecting this answer, sorry. – Subin Gopi Dec 17 '16 at 19:24