如何通过ctrl + V从剪贴板插入html到QTextEdit?

如何通过ctrl + V从剪贴板插入html到QTextEdit?

问题描述:

我有计划:如何通过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

试试这个:

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); 
     } 
    } 
}; 

不能直接将html代码粘贴到缩进空格中。尝试先将它复制到MS字上,然后从那里粘贴到其他任何地方。