gpt4 book ai didi

c++ - 如何调整 QTextEdit 以适合其内容

转载 作者:行者123 更新时间:2023-12-02 02:55:40 32 4
gpt4 key购买 nike

我正在开发一个 Qt 应用程序,我正在尝试找到一种方法来使用 QTextEdit 作为带有长文本而没有滚动条的标签。在我的用户界面中,我有一个 QScrollArea,在其中我想放置几个 QTextEdit 小部件,并且我只想在 QScrollArea 内使用滚动。问题是,无论我如何尝试调整 QTextEdit 的大小,它似乎都有最大高度和文本剪切,即使我手动设置大小和 QTextEdit::size返回正确的值。

我对QLabel做了同样的事情,它工作得很好,但在这种情况下,我需要一些仅在QTextEdit中提供的方法。

我找到了这篇文章: Resizing QT's QTextEdit to Match Text Height: maximumViewportSize()

给出的答案如下:

I have solved this issue. There were 2 things that I had to do to get it to work:

  1. Walk up the widget hierarchy and make sure all the size policies made sense to ensure that if any child widget wanted to be big/small, then the parent widget would want to be the same thing.
  2. This is the main source of the fix. It turns out that since the QTextEdit is inside a QFrame that is the main widget in a QScrollArea, the QScrollArea has a constraint that it will not resize the internal widget unless the "widgetResizable" property is true. The documentation for that is here: http://doc.qt.io/qt-4.8/qscrollarea.html#widgetResizable-prop. The documentation was not clear to me until I played around with this setting and got it to work. From the docs, it seems that this property only deals with times where the main scroll area wants to resize a widget (i.e. from parent to child). It actually means that if the main widget in the scroll area wants to ever resize (i.e. child to parent), then this setting has to be set to true. So, the moral of the story is that the QTextEdit code was correct in overriding sizeHint, but the QScrollArea was ignoring the value returned from the main frame's sizeHint.

问题是我不知道如何访问QTextEdit的 QScrollArea以启用widgetResizing。任何人都可以解释我如何实现此目的或建议调整 QTextEdit 大小以完美适应其内容的不同方法吗?

最佳答案

这将允许文本框的高度根据需要进行更改。您也可以稍微编辑代码来处理宽度。

connect( m_textField, SIGNAL( textChanged() ), this, SLOT( onTextChanged() ) );

void MyClass::onTextChanged()
{
QSize size = m_textField->document()->size().toSize();

m_textField->setFixedHeight( size.height() + 3 );
}

关于c++ - 如何调整 QTextEdit 以适合其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47710329/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com