QPlainTextEdit - setViewportMargins,受保护

时间:2017-01-12 14:32:14

标签: c++ qt qplaintextedit

我有一个带文本编辑的简单应用程序 - QPlainTextEdit,由qt designer创建。我只需要从mainwindow.cpp setViewportMargins.But我得到以下错误信息 - void QAbstractScrollArea :: setViewportMargins(int,int,int,int)'受到保护。

代码:

ui->textEdit->setViewportMargins(10,10,10,10);

有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

为了使用QPlainTextEdit的受保护方法,你需要对它进行子类化,如下所示:

class MyPlainTextEdit: public QPlainTextEdit
{
    Q_OBJECT
public:
    MyPlainTextEdit(QWidget* parent=0):QPlainTextEdit(parent){}
    //ADD A PUBLIC METHOD
    void publicSetViewportMargins(int left, int top, int right, int bottom)
    {
        setViewportMargins(left ,top, right, bottom);
    }
    //OR
protected:
    void setViewportMargins(int left, int top, int right, int bottom)
    {
        //REIMPLEMENT METHOD HERE
    }
};

答案 1 :(得分:0)

受保护的函数只能在类中使用,因此会生成错误。我已经通过设计CustomPlainText类并将其推广到原始QPlainTextEdit来解决它,我在其中使用了setViewportMargins (10,10,10,10);。如果你想从课外访问该函数,我已经创建了函数CustomSetViewportMargins({args})

右键单击并选择:提升为..

enter image description here

写出类的名称和标题并添加它。

enter image description here

然后按推广。

enter image description here

<强> customplaintext.cpp

#ifndef CUSTOMPLAINTEXT_H
#define CUSTOMPLAINTEXT_H

#include <QPlainTextEdit>

class CustomPlainText:public QPlainTextEdit
{
    Q_OBJECT
public:
    CustomPlainText(QWidget * parent = 0);
    void CustomSetViewportMargins(int left, int top, int right, int bottom);
    void CustomSetViewportMargins(const QMargins & margins);
};

#endif // CUSTOMPLAINTEXT_H

<强> customplaintext.h

#include "customplaintext.h"

CustomPlainText::CustomPlainText(QWidget *parent): QPlainTextEdit(parent)
{
    setViewportMargins(10,10,10,10);
}

void CustomPlainText::CustomSetViewportMargins(int left, int top, int right, int bottom)
{
    setViewportMargins(left, top, right, bottom);
}

void CustomPlainText::CustomSetViewportMargins(const QMargins & margins)
{
    setViewportMargins(margins);
}

在:

enter image description here

后:

enter image description here

完整代码: https://github.com/eyllanesc/stackoverflow/tree/master/CustomPlainTextProject