QTextEdit根据文本内容的多少调整width()和height(),实现自适应的宽度和高度,同时右侧和下方均不出现滚动条。
根据https://bbs.csdn.net/topics/330151382里10楼给出的代码作一定的修改,如下:
QTextEdit的父窗口的构造函数:
ui->textEdit->resize(24, 42);
connect(ui->textEdit->document(),SIGNAL(contentsChanged()),this,SLOT(textAreaChanged()));
ui->textEdit->setLineWrapMode(QTextEdit::NoWrap);
槽函数:
void Widget::textAreaChanged()
{
QTextDocument *document=qobject_cast(sender());
document->adjustSize();
if(document)
{
QTextEdit *editor=qobject_cast(document->parent()->parent());
if(editor)
{
int newwidth = document->size().width() + 10;//10
int newheight = document->size().height() + 20;//20
if(newwidth != editor->width())
{
editor->setFixedWidth(newwidth);
}
if(newheight != editor->height())
{
editor->setFixedHeight(newheight);
}
}
}
}
将该功能转为PyQt的代码:
QTextEdit的父窗口的构造函数:
self.width = 24
self.height = 42
self.edit.resize(self.width, self.height)
self.document = self.edit.document()
self.document.contentsChanged.connect(self.textAreaChanged)
self.edit.setLineWrapMode(QTextEdit.NoWrap)
槽函数:
def textAreaChanged(self):
self.document.adjustSize()
newWidth = self.document.size().width() + 10
newHeight = self.document.size().height() + 20
if newWidth != self.edit.width():
self.edit.setFixedWidth(newWidth)
if newHeight != self.edit.height():
self.edit.setFixedHeight(newHeight)