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

来源:互联网 发布:淘宝葡萄酒 编辑:程序博客网 时间:2024/05/17 11:06

实验说明:通过一个按钮,选择一张图片,将图片添加到表格里,并且添加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_OBJECTpublic:    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_OBJECTpublic:    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 运行效果图










0 0