Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c++ - How can I copy a text from a sfml window?

I've got this sfml window that displays a text and now I want to make it markable so that you can copy the text. Any ideas how to do that?

sfml window with a text


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you just want to copy everything then just use

sf::Clipboard::setString(your_string_here);

If you want more features, here are some I implemented when I programmed a Code Editor in SFML.

I stored two indexes, the first is where the selection begins, and the second is where the section ends.

So in the string Hello World!, if you wanted to select World you would set the begin index to 6, and the end index to 10 or 11 (depending on whether you include the final character or not).

I render this using an sf::RectangleShape, since my editor supported multiple line selection boxes the code is more complicated, but for your example you would want to get the position of each character. I used my own text renderer, but SFML's sf::Text::findCharacterPos() should be able to help with that.

Hello World

Next the copy part, this is just

sf::Clipboard::setString(getSelected());

where getSelected() is

return std::string::substr(selection_begin, selection_end - selection_begin);

If you want pasting as well then it is also simple:

eraseSelected();
insertStringAtCursor(sf::Clipboard::getString());

Which are both simple string operations as well (std::string::erase and reset the selection indexes, and std::string::insert).

Finally, to let the user change what is selected, either holding shift and pressing the arrow keys or clicking and dragging are both common ways, the former being easier than the latter.

For the former, check if shift is held and then if left or right is pressed update the indexes.

For the latter, you will need to handle mouse events and dragging. When dragging begins, set one of the indexes, whilst the mouse is moving and is dragging set the other index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...