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

Categories

0 votes
267 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...