[英]Resizing a cell's height and Witdth and loading an image in QTableWidget
I want to make a 8*8 table with square cells ( a chess board ). 我想用正方形单元格制作一个8 * 8的桌子(一个棋盘)。 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)
. 我认为问题出在
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 QTableWidgetItem s 编辑:要设置图像,请在QTableWidgetItem上设置icon属性
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 !!!
我应该首先制作一个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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.