Qt问题添加表格小部件项目

时间:2015-03-22 13:55:57

标签: c++ qt sqlite qtablewidget qtablewidgetitem

我有一张发票表单,我用它来创建发票并显示存储发票的结果。当我试图从数据库中读回数据并显示它时,我收到错误

  

QTableWidget:无法插入已由另一个QTableWidget拥有的项目   QTableWidget:无法插入已由另一个QTableWidget拥有的项目   QTableWidget:无法插入已由另一个QTableWidget拥有的项目   QTableWidget:无法插入已由另一个QTableWidget拥有的项目   QTableWidget:无法插入已由另一个QTableWidget

拥有的项目

我不明白为什么会这样。我尝试运行的查询将返回4行。我的代码在

之下
QString CompanyID;
            int row = 0;
            ui->comboBox_Invoice_Account_Search->setCurrentIndex(1);
            QSqlQuery Account_Name_Query;
            QTableWidgetItem *Qty_Search = new QTableWidgetItem();
            QTableWidgetItem *Description_Search = new QTableWidgetItem();
            QTableWidgetItem *Product_Code_Search = new QTableWidgetItem();
            QTableWidgetItem *Unit_Price_Search = new QTableWidgetItem();
            QTableWidgetItem *Total_Price_Search = new QTableWidgetItem();
            while(Query.next())
            {
                CompanyID = Query.value(10).toString();
                //qDebug() << "CompanyID " << CompanyID;
                ui->lineEdit_Invoice_VAT->setText(Query.value(9).toString());
                ui->lineEdit_Invoice_Total->setText(Query.value(8).toString());
                ui->lineEdit_Goods_Total->setText(Query.value(7).toString());
                Qty_Search->setText(Query.value(3).toString());
                Description_Search->setText(Query.value(4).toString());
                Product_Code_Search->setText(Query.value(5).toString());
                Unit_Price_Search->setText(Query.value(6).toString());
                Total_Price_Search->setText(Query.value(7).toString());
                ui->tableWidget_Invoice->setItem(row, 0, Qty_Search);
                ui->tableWidget_Invoice->setItem(row, 1, Description_Search);
                ui->tableWidget_Invoice->setItem(row, 2, Product_Code_Search);
                ui->tableWidget_Invoice->setItem(row, 3, Unit_Price_Search);
                ui->tableWidget_Invoice->setItem(row, 4, Total_Price_Search);
                row++;
                Account_Name_Query.prepare("SELECT Company_Name FROM Customer WHERE Company_ID = '"+ CompanyID +"'");
                Account_Name_Query.exec();
                while(Account_Name_Query.next())
                {
                    ui->lineEdit_Invoice_Account->setText(Account_Name_Query.value(0).toString());
                }
            }

导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:4)

那是因为你试图将你在循环外创建的相同项目多次设置到同一个表中。将您的代码更改为:

while(Query.next())
{
    QTableWidgetItem *Qty_Search = new QTableWidgetItem();
    QTableWidgetItem *Description_Search = new QTableWidgetItem();
    QTableWidgetItem *Product_Code_Search = new QTableWidgetItem();
    QTableWidgetItem *Unit_Price_Search = new QTableWidgetItem();
    QTableWidgetItem *Total_Price_Search = new QTableWidgetItem();

    ...
}