qt 中如何向QTableWidget里大量添加数据?

实验说明:通过一个按钮,选择一张图片,将图片添加到表格里,并且添加1000条该数据

项目文件:

qt 中如何向QTableWidget里大量添加数据?_第1张图片

1 main.cpp

#include 
#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 
#include 
#include 
#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<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 
#include 
#include 

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 运行效果图

qt 中如何向QTableWidget里大量添加数据?_第2张图片


qt 中如何向QTableWidget里大量添加数据?_第3张图片

qt 中如何向QTableWidget里大量添加数据?_第4张图片






你可能感兴趣的:(Qt,Qt开发总结)