繁体   English   中英

QT小部件指针

[英]QT Widget Pointer

我对QT相当陌生,正在努力使一个基本的绘画示例能够正常工作。 我正在创建一个游戏,该游戏在我的主游戏控制器中实例化一个小部件。 我想将此传递给多个不同的对象,以便每个对象可以拥有自己的paintEvent并相应地绘制其对象。 (例如,角色会单独绘画,风景等)

这是我的“动画对象”标题:

class Animated_object: public QWidget {

    public:
        Animated_object(char * _image_url, QWidget * window);
        ~Animated_object();

    protected:
        QImage * get_image();//this will return the image for this object
        QRect * get_rectangle();//this will return the rectangle of coordinates for this point


    protected:
        virtual void paintEvent(QPaintEvent * event) = 0;
        virtual void set_image(char * _image_url) = 0;


    protected:
        QWidget * window;
        char * image_url;//this is the imageurl
        QImage * image;
        QRect * rectangle;

};

我的动画对象构造器:

Animated_object::Animated_object(char * _image_url, QWidget * _window) : QWidget(_window) {....}

这是我的角色标头(字符继承自animated_object)

class Character : public Animated_object {

    public:
        Character(QWidget * _window);   
        ~Character();
        void operator()();//this is the operator for the character class -- this is responsible for running the character
        void set_image(char * _image_url) {};
        void paintEvent(QPaintEvent * event);

};

我通过向构造函数传递主窗口小部件指针来实例化字符。 因此,我还有另一个可以调用多个字符的类,它们将全部绘制到同一个小部件上(希望如此)。

我的角色paintEvent看起来像这样:

void Character::paintEvent(QPaintEvent * event) {

    QPainter painter(this);//pass it in window to ensure that it is painting on the correct widget!

    cout << "PAINT EVENT " << endl;
    QFont font("Courier", 15, QFont::DemiBold);
    QFontMetrics fm(font);
    int textWidth = fm.width("Game Over");

    painter.setFont(font);

    painter.translate(QPoint(50, 50));
    painter.drawText(10, 10, "Game Over");

}

它被调用,(我用std :: cout来测试),但是没有画任何东西。

最后,这是我的主窗口小部件的调用位置。

Hill_hopper::Hill_hopper(): Game(500,500, "Hill Hopper") {

    Character * character = new Character(window);

    window->show();
    application->exec();


}

这是游戏构造函数:

Game::Game(int _height, int _width, char * title): height(_height), width(_width) {


    int counter = 0;
    char ** args;


    application = new QApplication(counter, args);

    window = new QWidget();

    desktop = QApplication::desktop();

    this->set_parameters(title);

}

任何帮助将不胜感激

看起来您的标头中缺少Q_OBJECT宏。 虽然无论如何都可能不是问题。

无论如何,我建议您使用Qt Creator来创建新的类,它将为您创建.h和.cpp文件框架,以避免忘记这样的内容。

对于快速更新的游戏,您可能应该只有一个游戏区域小部件,您可以在其中绘制所有移动的内容。 如果仅绘制QPixMaps(没有直接文本或线条绘制,请先将文本片段转换为QPixmaps),然后只需将小部件转换为QGLWidget,即可非常快速地旋转和缩放QPixMap“精灵”,而无需自己编写任何OpenGL代码。但是如果建议的QGraphicsView足够快,那么它将为您做很多工作,您应该首先尝试一下。

您应该使用QGraphicsView窗口小部件,它是为这种思考而设计的。 QGraphicsView的场景( QGraphicsScene )中,您可以直接添加小部件。 内置系统将管理您的小部件并在需要时触发Paint事件。 此外,您还具有许多有用的功能来查找,移动等小部件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM