如何解决QGraphicsScene中什么也不显示
| 我正在尝试使用qgraphicsview qgraphicsitem创建像国际象棋这样的场景。 我正在尝试尝试创建它的官方示例,但是没有显示任何内容。代码几乎一样。首先,我想知道我的Cell课程。所以我只想画一个矩形。但是没有任何显示。下面是我的代码,有人可以帮帮我。我在Windows 7上使用Qt 4.7 单元格class Cell : public QGraphicsItem
{
//Q_OBJECT;
public:
Cell(const QColor &color,int x,int y);
QRectF boundingRect() const;
void paint(QPainter *painter,const qstyleOptionGraphicsItem *option,QWidget *widget);
private:
int x,y;
public:
QColor color;
protected:
void mousepressEvent(QGraphicsSceneMouseEvent *event);
};
单元格
Cell::Cell(const QColor &color,int y)
{
this->x=x;
this->y=y;
this->color=color;
setAcceptedMouseButtons(Qt::LeftButton);
}
QRectF Cell::boundingRect() const
{
return QRectF(0,30,15);
}
void Cell::paint(QPainter *painter,QWidget *widget)
{
QBrush b=painter->brush();
painter->setBrush(QColor::fromrgb(0,255));
painter->drawRect(0,15);
painter->fillRect(this->boundingRect(),QColor::fromrgb(0,255));
painter->setBrush(b);
return;
}
void Cell::mousepressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mouseMoveEvent(event);
this->color=QColor::fromrgb(0,0);
update();
}
视图
class View : public qframe
{
Q_OBJECT
public:
QGraphicsView *getview() const;
public:
View(QWidget *parent);
private:
QGraphicsView *graphicsView;
};
view.cpp
View::View(QWidget *parent)
:qframe(parent)
{
graphicsView = new QGraphicsView;
graphicsView->setRenderHint(QPainter::Antialiasing,false);
graphicsView->setoptimizationFlags(QGraphicsView::DontSavePainterState);
graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
}
QGraphicsView *View::getview() const
{
return graphicsView;
}
主窗口
class MainWindow : public QWidget
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
void populateScene();
QGraphicsScene *scene;
};
主窗口
MainWindow::MainWindow(QWidget *parent) :
QWidget(parent)
{
populateScene();
View *v=new View(0);
v->getview()->setScene(scene);
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(v);
setLayout(layout);
}
MainWindow::~MainWindow()
{
}
void MainWindow::populateScene()
{
scene=new QGraphicsScene();
for(int x=0;x<30;x++)
{
for(int y=0;y<20;y++)
{
QGraphicsItem *item=new Cell(QColor::fromrgb(0,255,255),15);
item->setPos(QPointF(30,15));
scene->addItem(item);
}
}
}
main.cpp
QApplication a(argc,argv);
MainWindow w;
w.show();
return a.exec();
解决方法
您的QFrame不“拥有”您的QGraphicsView。因此,没有理由在其中显示视图。
只需更换
graphicsView = new QGraphicsView;
与:
graphicsView = new QGraphicsView(this);
并且不要忘记调整窗口大小(或在代码中设置最小大小),否则,您可能会认为它不起作用=)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。