在QT中,QTableWidget处理二维表格的功能很强大(QTableView更强大),但有时我们只想让它显示少量数据(文字和图片),这时,使用QTableWidget就有点不方便了(个人感觉)。
所以我对QTableWidget再做了一次封装(SimpleTable类),让它在处理小型表格时更方便。
代码很简单,要解释的就写在注释里面了,欢迎大家使用。
如果大家发现这个类的BUG的话,欢迎提出,大家共同学习。
上代码:
- #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
-
-
- #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;
- }
-
-
- QTableWidgetItem *titem = item(cx, cy);
- if( NULL == titem )
- titem = new QTableWidgetItem;
- titem->setText(text);
- titem->setTextAlignment(alignment);
-
- 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;
- }
-
- 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;
- }
以下是一个简单的测试例子:
- #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();
- }
http://blog.csdn.net/small_qch/article/details/7674733
自己封装的一个简易的二维表类SimpleTable
原文:http://www.cnblogs.com/findumars/p/4993555.html