调整单元格的高度和宽度并在QTableWidget中加载图像

Omi*_*mid 2 qt resize image cell qtablewidget

我想用正方形单元格制作一个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();
}
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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

QIcon icon (pic);

table->item(0,0)->setIcon(icon);
Run Code Online (Sandbox Code Playgroud)

Cas*_*sey 5

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

  // 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);
Run Code Online (Sandbox Code Playgroud)

编辑:要设置图像,设置你的图标属性QTableWidgetItem小号