使用相同的单元格大小设置QGridLayout,QWidgets + QPainter.DrawImage不显示图像

时间:2013-10-19 10:39:26

标签: c++ qt cell qimage qgridlayout

首先,我将描述我想做的事情。我正在使用QT构建一个窗口应用程序。我本来想要做的就是说,我想要一个10x10的网格布局,所有单元格都是5x5,但不必先填充网格! 我用我的Widget类填充网格,扩展了QWidget类。 Widget或QWidget在构造函数上有一个.resize(w,h)所以我虽然这会在加载时限制小部件的w和h。然而,当我向网格添加一个小部件时,它只是在中心,下一个它想要的地方!

此外,在单击QWidget :: Widget并且blClicked = true时,应该加载图像..但不是! *有关详细信息,请参阅代码。

我基本上想要实现的是this,但qgridlayout中有0个qwidgets并且从左下角到左上角逐个增加它们等等。

谢谢!

以下代码:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPainter>
#include "widget.h"
#include <iostream>


class Widget : public QWidget
{
private:
    Q_OBJECT
    int x,y,w,h;
    bool blClicked;
    QImage img;
public:
    explicit Widget(QWidget *parent = 0);
    Widget(int x,int y,int w);
    void paintEvent(QPaintEvent* event);
    void mousePressEvent (QMouseEvent* event );
    int getX();
    int getY();
    QWidget* toQWidget();
};

#endif // WIDGET_H

widget.cpp

Widget::Widget(int x, int y,int w)
{
    this->x = x;
    this->y = y;
    this->w = w;
    this->h = w;
    this->resize(this->w,this->h);
    blClicked = false;
    img.load("car.png");
    update();
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setWindow(x,y,w,h);
    painter.drawRect(x,y,w,h);
    if(blClicked)
    {
        std::cout << "add image" << std::endl;
        painter.drawImage(x,y,img);
    }
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    std::cout << "mouse click pressed" << std::endl;
    blClicked = !blClicked;
    update();
}

mainwindow.cpp

void MainWindow::on_btnCreateMap_clicked()
{
    using namespace std;
    if(ui->lnHeight->text() != NULL && ui->lnWidth->text() != NULL)
    {
       std::cout << "click" << std::endl;
       try {
             width = stoi(ui->lnWidth->text().toStdString());
             height = stoi(ui->lnHeight->text().toStdString());
             //Mapper m(height,width);
             l.push_back(new Widget(2,2,10));
             ui->gridWidget->addWidget(l[l.size()-1]);
             for (int i = 0; i < l.size(); i++)
             {
                 std::cout << "list size" << l.size() << std::endl;
                 std::cout << "address" << l[i] << std::endl;
             }

       }
       catch (exception& e)
       {
            cout << "Standard exception: " << e.what() << endl;
       }
    }
}

0 个答案:

没有答案