[SOLVED] Displaying Table from plain text file using QTableView

  • Hi,
    I am retrieving information in the form of plain text files and i want to just display these tables in a neat way - which of the above is a better way. Any other suggestions ?

  • QTableView displays a model as tabel. QDataWidgetMapper ampps the data of a model to a bunch of widgets.
    So displaying data in a table is a typical task of QTableView and a "QAbstractTableModel":http://doc.qt.nokia.com/4.7/qabstracttablemodel.html derived class. But you have to parse your text and create the model. "See here for an example inside Qt documentation":http://doc.qt.nokia.com/4.7/model-view-programming.html

  • Well, if you want a table-kind display, go for the QTableView. If want a custom form designed by you, go for the QDataWidgetMapper.

  • If you are just displaying data parsed from a file, the I think QTableView is a better choice.

  • Thanks for all your suggestions. I decided to use QTableView.
    Following a previous post http://www.qtcentre.org/threads/17377-QTableView-memory-consumption , i have come up with the following code :
    Widget::Widget(QWidget *parent) :

    QTableView *mytable = new QTableView();
    QStandardItemModel *mytablemodel = new QStandardItemModel();
    int Max_num_of_Columns(8);
    int Max_Number_of_Lines(0);
    QFile file("/path/to/txt/file");
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
        qDebug() << "Error opening file";
    QTextStream InputDataFile&#40;&file&#41;;
    while (!InputDataFile.atEnd())
        QString line = InputDataFile.readLine();
        QStringList fields = line.split(" ");
        if (fields.size() == Max_num_of_Columns)
            for (int column=0; column< Max_num_of_Columns; column++)
                QStandardItem *item = new QStandardItem(fields[column]);
                mytablemodel->setItem(Max_Number_of_Lines, column, item);
            Max_Number_of_Lines++ ;


    I am unable to follow the model/view very well. Please help me figure out how to make this work. Just read a plain text file and display it in a tabular fashion.

    Thanks a lot.

  • This code works fine. It was messed up because of irregular spaces.
    I used @ str = "Some text\n\twith strange whitespace.";
    list = str.split(QRegExp("\s+"));@ to remove them.

    Hope this helps. Thanks.

  • Did you ever get this program to work because I can't seem to...where would i put:
    str = "Some text\n\twith strange whitespace.";
    list = str.split(QRegExp("\s+"));

  • You should put these lines at line 21 in the example above
    It should look like
    QString line = InputDataFile.readLine();
    QStringList fields = line.split(QRegExp("\s+"));

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.