In Qt, how can I register a QString to my System's clipboard, both quoted and non-quoted?

后端 未结 2 1316
南笙
南笙 2021-01-28 07:43

If I want a quoted string in my clipboard:

qDebug() << QString(\"Boat\\nProgramming\");

I then copy the output:

\"Boat\\n         


        
2条回答
  •  失恋的感觉
    2021-01-28 08:17

    Here is a very barebones solution that I implemented:

    // #include 
    // I had to swap to QGuiApplication to get the clipboard functionality.
    #include 
    #include 
    #include "whatever.h"
    
    int main(int argc, char *argv[])
    {
        QGuiApplication a(argc, argv);
        a.clipboard()->setText(QString("Boat\nProgramming")); // Quoted
        a.clipboard()->setText(QString("Boat\nProgramming")   // Non-Quoted
                               .replace("\n","\\n")
                               .replace("\t","\\t"));
    
        return 0;
    }
    

    As suggested by Basile Starynkevitch; these are not rigorously protected functions, but barebones solutions for small strings. Temporary in my case, and used purely for debugging purposes. Please do read his post, as he provides best practices to avoid code injection, and other security risks.

提交回复
热议问题