问:如何在QTableWidget中的单元格中插入字符串

ven*_*914 3 qstring qt insert qtablewidget qtablewidgetitem

可能重复: 用文件中的QString填充一些QTableWidgetItems

  1. 如何在运行时在QTableWidget中插入行?
  2. 如何在QTableWidget的单元格中插入硬编码字符串?

这是我在被卡住之前尝试过的...我已经使用Qt设计器插入了QTableWidget.

代码:mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
Run Code Online (Sandbox Code Playgroud)

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /*add stuff inside the table view*/
    QString line = "hello";
    for(int i=0; i<ui->tableWidget->rowCount(); i++)
    { 
        for(int j=0; j<ui->tableWidget->columnCount(); j++)
        {
            QTableWidgetItem *pCell = ui->tableWidget->item(i, j);
            if(!pCell)
            {
                pCell = new QTableWidgetItem;
                ui->tableWidget->setItem(i, j, pCell);
            }
            if(!line.isEmpty())
                pCell->setText(line);
        }
    }
#if 0
    const int rowAdder = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(rowAdder);
    QString str = "hello";
    ui->tableWidget->
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

ven*_*914 7

谢谢@Laszlo Papp,我删除了if(!line.isEmpty()).此外,我发现我错过了创建行和列,直到现在我只使用设计器创建了3列.我添加了两个用于添加行和列的语句.它奏效了.这是代码: -

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    /*add rows and columns*/
    ui->tableWidget->setRowCount(10);
    ui->tableWidget->setColumnCount(3);

    /*add stuff inside the table view*/
    QString line = "hello";
    for(int i=0; i<ui->tableWidget->rowCount(); i++)
    { 
        for(int j=0; j<ui->tableWidget->columnCount(); j++)
        {
            QTableWidgetItem *pCell = ui->tableWidget->item(i, j);
            if(!pCell)
            {
                pCell = new QTableWidgetItem;
                ui->tableWidget->setItem(i, j, pCell);
            }
            pCell->setText(line);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是预期和获得的输出.