从文件中用QString填充一些QTableWidgetItems [英] Filling some QTableWidgetItems with QString from file

查看:398
本文介绍了从文件中用QString填充一些QTableWidgetItems的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从程序导出的文件中填充QTableWidget,但是当我尝试将文本设置为表格单元格时,它们只是忽略了我,所以什么也没发生.

I'm trying to fill a QTableWidget from a file that was exported by my program, but when I try to set text to the table cells they just ignore me, nothing happens.

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();
    }
}

错误日志对象在屏幕上显示了从文件打开的正确值,但是未填充表格.发现任何问题吗?

The errorlog object shows on the screen the correct values opened from the file, however the table is not filled. Any problems found?

推荐答案

此行:

cell = new QTableWidgetItem(line); 

不执行您认为的操作.分配cell不会更改表中的任何内容– cell只是一个局部变量,覆盖它在其他地方没有任何作用.

doesn't do what you think it does. Assigning the cell doesn't change anything in the table – cell is just a local variable, overwriting it doesn't have any effect elsewhere.

您(可能)想做这样的事情:

You (probably) want to do something like this instead:

cell->setText(line);

或者(如果您确实不需要更改当前项目):

Or (if you don't really need to change the current item):

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

如果这些给您一个段错误,则表明您尚未设置表的窗口小部件项.在这种情况下,您应该执行以下操作:

If those give you a segfault, it's that you haven't set the table's widget items yet. In that case, you should do something like:

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

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

这将在第一次调用此函数时用QTableWidgetItem填充所有单元格,并随后重用它们.

This will populate all the cells with QTableWidgetItems the first time this function is called, and reuse them subsequently.

这篇关于从文件中用QString填充一些QTableWidgetItems的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆