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

时间:2017-08-13 19:43:20

标签: html c++ qt clipboard

我有节目:

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?

2 个答案:

答案 0 :(得分: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);
        }
    }
};

答案 1 :(得分:-1)

您不能直接使用缩进空格粘贴html代码。尝试先在MS word上复制它,然后从那里复制,粘贴到其他地方。