1. 程式人生 > >qt 中如何向QTableWidget裡大量新增資料?

qt 中如何向QTableWidget裡大量新增資料?

實驗說明:通過一個按鈕,選擇一張圖片,將圖片新增到表格裡,並且新增1000條該資料

專案檔案:


1 main.cpp

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

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

    return a.exec();
}
2 mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtGui>
#include <QtCore>
#include "tablethread.h"

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:

    void getPathSlot(QString);

    void on_AddData_clicked();

private:
    Ui::MainWindow *ui;
    TableThread *tablethread;
    QTableWidget *table;
    QString path;

};

#endif // MAINWINDOW_H
3 mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    table=new QTableWidget;
    table->setColumnCount(1);
    QStringList header;
    header<<tr("File Path");
    table->setHorizontalHeaderLabels(header);
    table->horizontalHeader()->resizeSection(0,300);
    ui->scrollArea->setWidget(table);

    connect(tablethread,SIGNAL(getPath(QString)),this,SLOT(getPathSlot(QString)));

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::getPathSlot(QString path)
{
    table->setRowCount(table->rowCount()+1);
    QTableWidgetItem *item=new QTableWidgetItem(path);
    item->setCheckState(Qt::Unchecked);
    item->setIcon(QIcon(path));
    table->setItem(table->rowCount()-1,0,item);
}


void MainWindow::on_AddData_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    "./",
                                                    tr("Images (*.png *.xpm *.jpg)"));

   tablethread->getFile(fileName);
   tablethread->start();
}
4 tablethread.h
#ifndef TABLETHREAD_H
#define TABLETHREAD_H

#include <QThread>
#include <QtGui>
#include <QtCore>

class TableThread : public QThread
{
    Q_OBJECT
public:
    explicit TableThread(QObject *parent = 0);
    void run();
    void getFile(QString);

    QString mypath;
    int i; //資料行數

signals:
    void getPath(QString);//自定義訊號
};

#endif // TABLETHREAD_H
5 tablethread.cpp
#include "tablethread.h"

TableThread::TableThread(QObject *parent) :
    QThread(parent)
{
    i=0;
}

void TableThread::run()
{
    while(i<100)
    {
        i++;
        emit getPath(mypath);
        msleep(50);
    }
}

void TableThread::getFile(QString file)
{
    mypath=file;
}

6 執行效果圖