0

プログラムによってエクスポートされたファイルから QTableWidget を入力しようとしていますが、表のセルにテキストを設定しようとすると、無視されて何も起こりません。

void MainWindow::on_actionOpen_Project_triggered()
{
    QString line, fileName;
    fileName = QFileDialog::getOpenFileName(this,tr("Open Project"), "", tr("Project Files (*.project)"));

    if(!fileName.isEmpty()){

        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
        QTextStream in(&file);

        for(int i=0;i<ui->code->rowCount();i++){ // goes through table rows
            for(int j=0;j<ui->code->columnCount();j++){ // through table columns

                ui->code->setCurrentCell(i,j);
                QTableWidgetItem *cell = ui->code->currentItem();
                in >> line;

                if(!line.isEmpty()){
                    cell = new QTableWidgetItem(line); // relates the pointer to a new object, because the table is empty.
                    ui->errorlog->append(line); // just for checking if the string is correct visually.
                }
            }
        }
        file.close();
    }
}

errorlog オブジェクトは、ファイルから開かれた正しい値を画面に表示しますが、テーブルには値が入力されていません。何か問題が見つかりましたか?

4

1 に答える 1

0

この行:

cell = new QTableWidgetItem(line); 

あなたが思っていることをしません。を代入しcellても、テーブル内の何も変更されません –cellは単なるローカル変数であり、上書きしても他の場所では何の効果もありません。

あなたは(おそらく)代わりに次のようなことをしたいでしょう:

cell->setText(line);

または (現在の項目を変更する必要がない場合):

ui->code->item(i,j)->setText(line);

これらでセグメンテーション違反が発生する場合は、テーブルのウィジェット項目をまだ設定していないということです。その場合、次のようにする必要があります。

QTableWidgetItem *cell = ui->code->item(i,j);
if (!cell) {
  cell = new QTableWidgetItem;
  ui->code->setItem(i,j,cell);
}

if (!line.isEmpty()) {
  cell->setText(line);
}

これにより、この関数が最初に呼び出されたときにすべてのセルにQTableWidgetItems が入力され、その後それらが再利用されます。

于 2012-05-04T17:36:27.927 に答える