在QT中,QTableWidget处理二维表格的功能很强大(QTableView更强大),但有时我们只想让它显示少量数据(文字和图片),这时,使用QTableWidget就有点不方便了(个人感觉)。
所以我对QTableWidget再做了一次封装(SimpleTable类),让它在处理小型表格时更方便。
代码很简单,要解释的就写在注释里面了,欢迎大家使用。
所以我对QTableWidget再做了一次封装(SimpleTable类),让它在处理小型表格时更方便。
代码很简单,要解释的就写在注释里面了,欢迎大家使用。
如果大家发现这个类的BUG的话,欢迎提出,大家共同学习。
上代码:
//simpletable.h
#ifndef SIMPLETABLE_H_
#define SIMPLETABLE_H_
#include <QtCore>
#include <QtGui>
class SimpleTable : public QTableWidget
{
Q_OBJECT
private:
public:
//构造函数,无实际内容,直接调用的构造函数
SimpleTable(QWidget *parent = 0) : QTableWidget(parent) { }
SimpleTable(int row, int column, QWidget *parent = 0)
: QTableWidget(row, column, parent) { }
//设置某个单元格中的文字
void SetCellText( int cx, int cy, const QString &text,
int alignment = Qt::AlignLeft,
const QIcon icon = QIcon() );
//在某个单元格中放置一张小图片
void SetCellPixmap(int cx, int cy, const QPixmap &pixmap,
Qt::Alignment alignment = Qt::AlignCenter);
//获取某个单元格中的字符串(如果没有,就返回一个空字符串)
QString GetCellText(int cx, int cy);
//获取某个单元格的图片(如果没有,就返回一张空图片)
QPixmap GetCellPixmap(int cx, int cy);
};
#endif
//simpletable.cpp
#include "simpletable.h"
void SimpleTable::SetCellText(int cx, int cy, const QString &text,
int alignment, const QIcon icon)
{
//检查是否越界
if( cx>=rowCount() || cy>=columnCount() )
{
qDebug() << "Fail, Out of Range";
return;
}
//如果此单元格中已经有item了,就直接更改item中的内容
//否则,新建一个item
QTableWidgetItem *titem = item(cx, cy);
if( NULL == titem )
titem = new QTableWidgetItem;
titem->setText(text);
titem->setTextAlignment(alignment);
//如果图标不为空,就为此item设置图标
if( !icon.isNull() )
titem->setIcon(icon);
setItem(cx, cy, titem);
}
void SimpleTable::SetCellPixmap(int cx, int cy, const QPixmap &pixmap,
Qt::Alignment alignment)
{
if( cx>=rowCount() || cy>=columnCount() )
{
qDebug() << "Fail, Out of Range";
return;
}
//在item中设置图片有很多方法,但我还是觉得在其中放置带图片一个Label最简单
QLabel *label = new QLabel(this);
label->setAlignment(alignment);
label->setPixmap(pixmap);
setCellWidget(cx, cy, label);
}
QString SimpleTable::GetCellText(int cx, int cy)
{
QString result;
if( cx>=rowCount() || cy>=columnCount() )
{
qDebug() << "Fail, Out of Range";
return result;
}
QTableWidgetItem *titem = item(cx, cy);
if( NULL != titem )
{
result = titem->text();
}
return result;
}
QPixmap SimpleTable::GetCellPixmap(int cx, int cy)
{
QPixmap result;
if( cx>=rowCount() || cy>=columnCount() )
{
qDebug() << "Fail, Out of Range";
return result;
}
QTableWidgetItem *titem = item(cx, cy);
if( NULL == titem )
return result;
QLabel *label = dynamic_cast<QLabel*>( cellWidget(cx, cy) );
result = *label->pixmap();
return result;
}
以下是一个简单的测试例子:
//main.cpp
//测试例子
#include "simpletable.h"
int main(int argc, char **argv)
{
QApplication app(argc, argv);
SimpleTable table(20, 10);
for(int i=0; i<20; i++)
{
for(int j=0; j<10; j++)
{
table.SetCellText(i, j, QString::number(i*10+j));
}
}
table.show();
return app.exec();
}