3

我想用方形单元格(棋盘)制作一个 8*8 的桌子。现在我有了制作表格的代码,但不知道如何将单元格调整为方形。

我还想将碎片的图片放入单元格中。我该怎么做这些?

这是我的代码:

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QHBoxLayout>
#include <QTableWidget>

class Table : public QWidget
{
  public:
    Table(QWidget *parent = 0);

};


Table::Table(QWidget *parent)
    : QWidget(parent)
{
  QHBoxLayout *hbox = new QHBoxLayout(this);

  QTableWidget *table = new QTableWidget(8 , 8 , this);

  hbox->addWidget(table);
  setLayout(hbox);
}



int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Table t;

    t.show();


    return a.exec();
}

编辑:

如果有人也可以帮助我将图像加载为单元格的背景,将不胜感激!我使用此代码,编译器不会产生错误,但程序无法运行。我认为问题出在table->item(0,0). 我应该先初始化它吗?

QString fileName = "1.bmp";
QPixmap pic (fileName);

QIcon icon (pic);

table->item(0,0)->setIcon(icon);
4

2 回答 2

7

要使单元格呈方形,请执行以下操作:

  // set the default size, here i've set it to 20px by 20x
  table->horizontalHeader()->setDefaultSectionSize(20);
  table->verticalHeader()->setDefaultSectionSize(20);
  // set the resize mode to fixed, so the user cannot change the height/width
  table->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
  table->verticalHeader()->setResizeMode(QHeaderView::Fixed);

编辑:要设置图像,请在 QTableWidgetItem 上设置图标属性

于 2010-07-08T19:00:37.743 回答
1

在搜索和搜索和搜索之后......我终于得到了答案。我应该首先制作一个 QBrush 对象并将其设置为 QtableWidgetItem 的背景,然后使用 table->setItem !

QString fileName = "/1.bmp";
QPixmap pic (fileName);

QBrush brush(pic);

QTableWidgetItem* item = new QTableWidgetItem();
item->setBackground(brush);

table->setItem(0,0,item);
于 2010-07-09T10:10:16.290 回答