QT小部件指针

QT Widget Pointer

本文关键字:指针 小部 QT      更新时间:2023-10-16

我是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宏。尽管如果它被调用,这可能不是问题所在。

无论如何,我建议您使用QtCreator来创建新的类,它将为您创建.h和.cpp文件骨架,避免忘记这样的东西。

对于一个快速更新的游戏,你可能只需要一个游戏区域小部件,在那里你可以画出所有移动的东西。如果您只绘制QPixMap(没有直接的文本或线条绘制,请先将文本片段转换为QPixMap),那么只需将小部件转换为QGLWidget即可快速旋转和缩放QPixMap"精灵",而无需自己编写任何OpenGL代码。但是,如果建议的QGraphicsView足够快,那么如果它对你有用的话,它会做很多事情,你应该先尝试一下。

您应该使用QGraphicsView小部件,它是为这种想法而设计的。在QGraphicsView的场景(QGraphicsScene)中,您可以直接添加小部件。内置系统将管理您的小部件,并在需要时激发绘制事件。此外,您还有很多有用的功能来查找、移动等小部件。