CoordinateSetter是第十章关于QTableWidget和QTableWidgetItem的一个例子,
在此例中作者在每个项中创建QTableWidgetItem实例,并将坐标值写到其中。我想像第四章中SpreadSheet例子那样,通过调用QTableWidget::setItemPrototype(),在需要时由QTableWidget实例自动生成项。但是改写后发现不能自动生成项,麻烦看谁能够给找出问题,谢谢。
头文件
#ifndef TESTTABLEWIDGET_H
#define TESTTABLEWIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
class QTableWidget;
QT_END_NAMESPACE
class TestTableWidget : public QWidget
{
Q_OBJECT
public:
explicit TestTableWidget(const QList<QPointF>* coord, QWidget *parent = 0);
private:
void addRow();
private:
QTableWidget* pTableWidget;
const QList<QPointF>* pCoordinates;
};
#endif // TESTTABLEWIDGET_H
实现文件
#include "testtablewidget.h"
#include <QTableWidget>
#include <QStringList>
#include <QTableWidgetItem>
#include <QVBoxLayout>
TestTableWidget::TestTableWidget(const QList<QPointF>* coord,
QWidget *parent) :
QWidget(parent),
pTableWidget(new QTableWidget(10, 2, this))
{
pCoordinates = coord;
QStringList strList;
strList.append(tr("X"));
strList.append(tr("Y"));
pTableWidget->setHorizontalHeaderLabels(strList);
pTableWidget->setItemPrototype(new QTableWidgetItem());
//set pTableWidget to be disabled for changing item.
//pTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
for (int row(0); row != pCoordinates->count(); ++row) {
QPointF point = pCoordinates->at(row);
//addRow();
pTableWidget->item(row, 0)->setText(QString::number(point.x()));
pTableWidget->item(row, 1)->setText(QString::number(point.y()));
}
QVBoxLayout* vBoxLayout(new QVBoxLayout(this));
vBoxLayout->addWidget(pTableWidget);
setLayout(vBoxLayout);
}
void TestTableWidget::addRow()
{
int row(pTableWidget->rowCount());
pTableWidget->insertRow(row);
/*
QTableWidgetItem* item0(new QTableWidgetItem());
item0->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft);
pTableWidget->setItem(row, 0, item0);
QTableWidgetItem* item1(new QTableWidgetItem());
item1->setTextAlignment(Qt::AlignBaseline | Qt::AlignRight);
pTableWidget->setItem(row, 1, item1);
pTableWidget->setCurrentCell(row, 0);
*/
}
main函数
#include <QtWidgets>
#include "coordinatesetter.h"
#include "testtablewidget.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QList<QPointF> coordinates;
coordinates << QPointF(0.0, 0.9)
<< QPointF(0.2, 11.0)
<< QPointF(0.4, 15.4)
<< QPointF(0.6, 12.9)
<< QPointF(0.8, 8.5)
<< QPointF(1.0, 7.1)
<< QPointF(1.2, 4.0)
<< QPointF(1.4, 13.6)
<< QPointF(1.6, 22.2)
<< QPointF(1.8, 22.2);
//CoordinateSetter coordinateSetter(&coordinates);
//coordinateSetter.show();
TestTableWidget coordinateSetter(&coordinates);
coordinateSetter.show();