显示来自另一个 Class 的 sf::Text 对象的文本。 SFML

Displaying text from a sf::Text object from another Class. SFML

我正在尝试创建一个 class,它将创建一个带有一些白色文本的黑框。它最终将能够根据发送到 class 的字符串来缩放框的大小。但是,首先,我不知道为什么文本不显示。感谢您的帮助。

这里是 TextBox.h

class TextBox{

public:

sf::RectangleShape rect;
sf::Text text;
sf::Font font;

TextBox(std::string str, sf::Font f);
sf::Text getText();

这是在 TextBox.cpp 中找到的 TextBox 构造函数。我发送给构造函数的 sf::Font 是由 SFML 设置的字体。

#include "TextBox.h"
#include "string"

TextBox::TextBox(std::string str, sf::Font font){

rect.setFillColor(sf::Color::Black);
rect.setPosition(20, 20);
rect.setSize(sf::Vector2f(120,120));

text.setFont(font);
text.setString(str);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);

text.setPosition(rect.getPosition());

}

这是 main.cpp 中的代码,应该同时显示 Rect 和 Text

sf::Font font;
if (!font.loadFromFile(resourcePath() + "sansation.ttf")) {
    return EXIT_FAILURE;
}

TextBox textBox("This Box", font);
textBox.text.setStyle(sf::Text::Bold);
// Start the game loop
while (window.isOpen())
{
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window: exit
        if (event.type == sf::Event::Closed) {
            window.close();
        }

        // Escape pressed: exit
        if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
            window.close();
        }
    }

    // Clear screen
    window.clear();

    window.draw(textBox.rect);
    window.draw(textBox.text);

    // Update the window
    window.display();

我尝试使用 public getText() 方法 returns 一个 sf::Text 对象,但它没有解决问题。 此外,我对 rect 所做的修改起作用并显示了 rect。正文不是。

谢谢你干杯

来自 sf::Text::setFont() method:

The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behavior is undefined.

.

在你的 TextBox 构造函数中,你将 font 作为副本 f 传递,在初始化 textBox 之后,字体副本 f 将被销毁,因此你的 textBox.text 没有显示。

修复它很简单:通过使用传递(常量)引用按原样传递 fontTextBox(std::string str, const sf::Font& f);

(您可能也想将 std::string 作为 const 引用传递)