[英]Resizing a cell's height and Witdth and loading an image in 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();
}
编辑:
如果有人也可以帮助我加载图像作为单元格的背景,将不胜感激! 我使用此代码,并且编译器不会生成错误,但是程序无法运行。 我认为问题出在table->item(0,0)
。 我应该先初始化吗?
QString fileName = "1.bmp";
QPixmap pic (fileName);
QIcon icon (pic);
table->item(0,0)->setIcon(icon);
要使单元格呈方形,请执行以下操作:
// 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上设置icon属性
经过搜索和搜索……我终于得到了答案。 我应该首先制作一个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.