2017-08-13 23 views
-2

我有計劃:如何通過ctrl + V從剪貼板插入html到QTextEdit?

int main(int argc, char *argv[]){ 
    QApplication app(argc, argv);  
    QTextEdit te; 
    te.setHtml("<!DOCTYPE html>" 
     "<html>" 
     "<body style = \"background-color:powderblue;\">" 
     "<h1>My First Heading</h1>" 
     "<p>My first paragraph.</p>" 
     "</body>" 
     "</html>"); 
    te.resize(500, 300); 
    te.show(); 
    return app.exec(); 
} 

這個程序創建如下窗口:

QTextEdit with html

我有另一個程序:

int main(int argc, char *argv[]){ 
    QApplication app(argc, argv);  
    QTextEdit te; 
    te.resize(500, 300); 
    te.show(); 
    return app.exec(); 
} 

但是,如果我複製文本

<!DOCTYPE html> 
<html> 
<body style="background-color:powderblue;"> 
<p>This is a paragraph.</p> 
<p>This is another paragraph.</p> 
</body> 
</html> 

通過按CTRL + V到由該程序創建的窗口剪貼板中,我看到:

window with plain html text

我如何重寫我的程序來顯示HTML作爲第一個圖像?

+0

就不好說了,如果你不顯示的代碼。當您鍵入文本而不是粘貼它時,行爲會有所不同嗎? – KjMag

+0

閱讀http://doc.qt.io/qt-5/qclipboard.html – hyde

+0

您可能還想閱讀http://doc.qt.io/qt-5/qtextedit.html#insertFromMimeData – hyde

回答

1

試試這個:

class TextEdit : public QTextEdit{ 
public: 
    TextEdit(QWidget *parent = 0): 
     QTextEdit(parent) 
    {} 
protected: 
    void insertFromMimeData(const QMimeData *source){ 
     if(source->hasText()){ 
      setHtml(source->text()); 
     } 
     else{ 
      QTextEdit::insertFromMimeData(source); 
     } 
    } 
}; 
0

不能直接將html代碼粘貼到縮進空格中。嘗試先將它複製到MS字上,然後從那裏粘貼到其他任何地方。

相關問題