如何使用html打印QTextDocument数据?

我的代码,但返回错误:

QString text_x = "Hello World!";

QTextDocument *doc = new QTextDocument(this);
doc->setUndoRedoEnabled(false);
doc->setHtml("<p><span style=\"color:#000000; font-weight:600\">"+text_x+"</span></p>");
doc->setTextWidth(width());
doc->setUseDesignMetrics(true);
doc->setDefaultTextOption(QTextOption(Qt::AlignHCenter));

QPainter *p = new QPainter(this);
p->setRenderHint(QPainter::Antialiasing, true);
p->begin(this);
doc->drawContents(p);
p->end();


错误:


  QPainter :: pen:画家不活跃QPainter :: setPen:画家不活跃QPainter :: pen:画家不活跃QPainter :: setPen:画家不活跃QPainter :: setPen:画家不活跃QPainter :: setPen:画家不活跃QPainter: :restore:不平衡的保存/恢复QPainter :: end:Painter不活动,已中止

最佳答案

正如我在评论中写道:您在paintEvent外部的小部件上绘图,这是一个问题。

这是您要求的示例代码:

class MyDocWidget : public QWidget {
    Q_OBJECT

public:
    explicit MyDocWidget(QWidget * parent = 0, Qt::WindowFlags f = 0)
         : QWidget(parent, f)
    {
        doc = new QTextDocument(this);
        doc->setUndoRedoEnabled(false);
    }

public slots:
    void setHtml(const QString &html) {
         doc->setHtml(html);
         update();
    }

protected:
    void paintEvent(QPaintEvent * event) {
         QPainter p(this);
         p.setRenderHint(QPainter::Antialiasing, true);
         doc->drawContents(&p);
    }

    void resizeEvent(QResizeEvent * event) {
         QWidget::resizeEvent(event);
         doc->setTextWidth(width());
         update();
    }

private:
    QTextDocument *doc;
}

关于c++ - 打印数据QTextDocument和QPainter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22614384/

10-13 06:29