QTextEdit 或 QTextBrowser 高度自適應

以下方法收集自網絡

使用 QTextDocumentcontentsChanged 信號可以解決此問題。

QTextEdit *editor = new QTextEdit(this);
...
connect(editor->document(),SIGNAL(contentsChanged()),this,SLOT(textAreaChanged()));
...

private slots:    
void textAreaChanged()
{
	QTextDocument *document=qobject_cast<QTextDocument*>(sender());  
	document->adjustSize();  
	if(document)
	{  
    	QTextEdit *editor=qobject_cast<QTextEdit*>(document->parent()->parent());  
    	if (editor)
    	{  
        	int newheight = document->size().rheight()+10;  
        	if (newheight != editor->height())
        	{  
            	editor->setFixedHeight(newheight);  
        	}  
	    }  
	} 
}

QTextBrowser 同上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章