Why not just
Qt Code:
  1. QString txt = "This is text with spaces";
  2. txt.replace(" ", "_");
To copy to clipboard, switch view to plain text mode