Search code examples
pythonpyqtpyqt4qtablewidgetqlineedit

retrieve value from QlineEdit inside QtableWidget in Pyqt4 Python


I am having trouble in Retrieving the Entered in QWidgetlineEdit box. Got C++ Implementation of the Same but unable to retrieve using Python,

    self.line = QtGui.QLineEdit() 
    i =0
    while(i<self.tableWidget.rowCount()):
    self.q = (QtGui.QLineEdit()).self.tableWidget.cellWidget(i, 1)
    j = self.line.text()
    print j
    i +=1

working code in c++:


QLineEdit* tmpLineEdit;
QString tmpString;
for(int row=0; row < moneyTableWidget.rowCount(); row++)
{
    tmpLineEdit = qobject_cast<QLineEdit *>(moneyTableWidget.cellWidget(row,1));
    tmpString = tmpLineEdit->text();

}

Solution

  • First of all the code that you provide with C ++ is dangerous since nobody guarantees that the cellWidget that is returned is a QLineEdit so a verification improves the code:

    QString tmpString;
    for(int row=0; row < moneyTableWidget.rowCount(); row++)
    {
        if(QLineEdit * tmpLineEdit = qobject_cast<QLineEdit *>(moneyTableWidget.cellWidget(row,1)))
            tmpString = tmpLineEdit->text();
    }
    

    In the case of python it is not necessary to do a casting but you have to verify that the widget that returns cellWidget is a QLineEdit using isinstance():

    tmpString = ""
    for row in range(self.tableWidget.rowCount()):
        widget = self.tableWidget.cellWidget(row, 1)
        if isinstance(widget, QtGui.QLineEdit):
            tmpString = widget.text()