简体   繁体   English

如何在qtablewidget或qtableview的第一列中从文件中插入数据?

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

I would like to insert a list of users from a file into the first row of a tablewidget or tableview. 我想将文件中的用户列表插入tablewidget或tableview的第一行。 I am currently trying it out with a tablewidget. 我目前正在尝试使用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. 基本上,如果您查看图像,则我将尝试完全执行该操作,然后稍后我将添加一个确定按钮以执行操作。

去做

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_())

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 假设您有一个文件users.txt ,该文件每行包含一个名称,例如

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_())
#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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM