Search code examples
c++qtqt5qtexteditqclipboard

QClipboard and selectedText() are not equal in QTextEdit


I am doing something in the QTextEdit. I write a slot for the QClipboard::changed() signal. In the slot, how can I tell if the text in the clipboard is from my app (not from other apps outside)?

My solution is to compare the text in the clipboard and the selected text:

mimeData->text() == textCursor()->selectedText()

However, I found that when I selected multiple lines and copied it. The selectedText() handle the \n as 0 while the mimeData handle it as \n (that is 10). So mimeData->text() != textCursor()->selectedText().

By the way, what does QClipboard::ownsClipboard() mean? Is it what I am looking for?

Any help? Thanks!


Solution

  • According to the documentation:

    bool QClipboard::ownsClipboard() const

    Returns true if this clipboard object owns the clipboard data; otherwise returns false.

    So it is what you are looking for.

    clipboard = QApplication::clipboard();
        connect(clipboard, SIGNAL(changed(QClipboard::Mode)), this, SLOT(your_slot()));
    

    slot:

    void {your class}::your_slot()
    {
        if(clipboard->ownsClipboard())
            qDebug()<< "own";
        else
            qDebug()<< "not his own";
    }
    

    Transcribing from the documentation of selectedText()

    Returns the current selection's text (which may be empty). This only returns the text, with no rich text formatting information. If you want a document fragment (i.e. formatted rich text) use selection() instead.

    Note: If the selection obtained from an editor spans a line break, the text will contain a Unicode U+2029 paragraph separator character instead of a newline \n character. Use QString::replace() to replace these characters with newlines.