如果我将文本文件加载到QTextStream中,那么我如何用其数据填充TableWidget?文本文件以制表符分隔。以下是我到目前为止的情况:
void MainWindow::startParsing()
{
QStringList stringList;
int countRows;
QTextStream in(&textFile);
QString line;
if (textFile.open(QIODevice::ReadOnly))
{
do
{
line = in.readLine();
stringList << line.split("\t", QString::SkipEmptyParts);
}
while (!in.atEnd());
}
QSet<QString> set = stringList.toSet();
foreach (const QString &value, set)
qDebug() << value;
countRows = stringList.count();
//--- define the table's shape ---
ui->tableWidget_inputPreview->setRowCount(countRows);
ui->tableWidget_inputPreview->setColumnCount(6);
//--- create the horizontal (column) headers ---
QStringList horzHeaders;
horzHeaders << "HostName" << "Host IP" << "Area" << "Host Interface"
<< "Router to Ext Network" << "Ext Routes";
ui->tableWidget_inputPreview->setHorizontalHeaderLabels( horzHeaders );
//--- create the vertical (row) headers ---
QStringList vertHeaders;
ui->tableWidget_inputPreview->setVerticalHeaderLabels( vertHeaders );
//--- populate the table widget with data from txt file ---
// TODO: insert data into table
}
以下是我正在使用的文本文件的示例:
#TEST 1
#HostName HostIP Area Host Interface Router to Ext NW Number of Ext Routes
test1 9.1.1.1 0.0.0.0
OMG_LOL_101 128.12.101.2 0.0.0.0
OMG_LOL_102 128.12.102.9 0.0.0.0 128.112.102.9 128.112.102.10 100
WTF_BBQ_149 128.20.180.2 0.0.0.0
#HITL 2
#HostName HostIP Area Host Interface Router to Ext NW Number of Ext Routes
test2 9.1.1.2 0.0.0.0
WTF_BBQ_111 128.15.110.2 0.0.0.0
WTF_BBQ_112 128.15.111.2 0.0.0.0
WTF_BBQ_113 128.15.112.2 0.0.0.0 128.115.112.9 128.115.112.10 100
答案 0 :(得分:3)
QTextStream in(&file);
QList< QStringList > lists;
QString line;
do {
line = in.readLine();
lists << line.split("\t");
} while (!line.isNull())
// Set the table size (assuming the rows are all the same length).
tableWidget.setRowCount( lists.size() );
tableWidget.setColumnCount( lists[0].size() );
for ( int row = 0; row < lists.size(); ++row ) {
for ( int column = 0; column < lists[row].size(); ++column ) {
tableWidget.setItem(row, column, new QTableWidgetItem(lists[row][column]));
}
}