开发者

Resizing a cell's height and Witdth and loading an image in QTableWidget

开发者 https://www.devze.com 2023-01-06 16:47 出处:网络
I want to make a 8*8 table with square cells ( a chess board ). Now I have the code to make the table but don\'t know how to resize the cells to be square shaped.

I want to make a 8*8 table with square cells ( a chess board ). Now I have the code to make the table but don't know how to resize the cells to be square shaped.

I also want to put pictures of pieces into the cells. How 开发者_如何学运维should I do these?

here is the code i have:

#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();
}

EDIT:

If anyone can help me with loading an image as the background of cell too, it would be very appreciated! I use this code and compiler does not generate an error but program fails to run. I think the problem is with the table->item(0,0). Should I initialize it first?

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

QIcon icon (pic);

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


To make the cells square shaped do something like this:

  // 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);

Edit: To set the images, set the icon attribute on your QTableWidgetItems


after searching and searching and searching.... I finally got the answer. I should first make a QBrush object and set it as a background of a QtableWidgetItem and then use table->setItem !!!

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

QBrush brush(pic);

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

table->setItem(0,0,item);
0

精彩评论

暂无评论...
验证码 换一张
取 消