2012-05-15 23 views
5
文本文件填充表格部件

我是新來的Qt,需要一些幫助,下面:從Qt中

我想創建一個包含表格部件的GUI由信息填充從界定的標籤來文本文件。在我的GUI中,用戶將首先瀏覽文本文件,然後它將顯示Table Widget中的內容。我已經完成了瀏覽部分,但是如何將文本文件中的數據加載到Table Widget中?

+0

,這個問題很模糊,您使用MVC或「傳統的」小工具?表格小部件是2D的,那麼文本如何在表格中進行佈置? – cmannett85

+0

在Qt Creator中,有一個叫做Table Widget的GUI控件,這就是我正在使用的。我認爲這個問題很直接。我想在我的GUI中使用製表符分隔的文本文件作爲數據源填充表格。如果使用Table Widget,這不是最好的方法,那麼我接受其他建議。正如我所提到的,我是Qt新手。 –

+0

如果您希望僅在2D網格中顯示文本,而不與其他任何小部件共享數據,那麼'QTableWidget'是最好的選擇。如果你只在你的文章中提出一個問題,你也會得到更好的迴應:加載一個文本文件,解析成單獨的字符串,然後推送到一個表格小部件;是三個完全不同的流程,如果在本網站或文檔中沒有解釋每個流程,我會感到驚訝。 – cmannett85

回答

8

這是兩個步驟,解析文件,然後將其推入小部件。

我抓住QFile documentation這些行。

QFile file("in.txt"); 
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) 
    return; 

while (!file.atEnd()) { 
    QByteArray line = file.readLine(); 
    process_line(line); 
} 

你process_line功能應該是這樣的:

static int row = 0; 
QStringList ss = line.split('\t'); 

if(ui->tableWidget->rowCount() < row + 1) 
    ui->tableWidget->setRowCount(row + 1); 
if(ui->tableWidget->columnCount() < ss.size()) 
    ui->tableWidget->setColumnCount(ss.size()); 

for(int column = 0; column < ss.size(); column++) 
{ 
    QTableWidgetItem *newItem = new QTableWidgetItem(ss.at(column)); 
    ui->tableWidget->setItem(row, column, newItem); 
} 

row++; 

更多有關操縱QTableWidgets,檢查documentation。對於在Qt Creator中使用GUI構建器的新用戶,首先要搞清楚它是非常棘手的。

最終,我會建議切換到在他們的所有examples中執行的方式來構建GUI ...通過在代碼中手動添加所有內容而不是拖放操作。

-2

對不起......

void squidlogreader_::process_line(QString line) 
{ 
    static int row = 0; 
    QStringList ss = line.split('\t'); 

    if(ui->tableWidget->rowCount() < row + 1) 
    ui->tableWidget->setRowCount(row + 1); 
    if(ui->tableWidget->columnCount() < ss.size()) 
    ui->tableWidget->setColumnCount(ss.size()); 

    for(int column = 0; column < ss.size(); column++) 
    { 
    QTableWidgetItem *newItem = new QTableWidgetItem(ss.at(column)); 
    ui->tableWidget->setItem(row, column, newItem); 
    } 

    row++; 

} 
void squidlogreader_::on_pushButton_clicked() 
{ 
    QFile file("in.txt"); 
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) 
     return; 

    while (!file.atEnd()) { 
     QString line = file.readLine(); 
     process_line(line); 
    }