我有一個QTextEdit作爲「顯示器」(可編輯爲false)。它顯示的文字是字跡包裝。現在我希望設置此文本框的高度,以便文本完全適合(同時還要考慮最大高度)。qtextedit - 調整大小以適合
基本上,佈局下面的小部件(在同一垂直佈局中)應儘可能多地佔用空間。
這怎麼能最容易實現?
我有一個QTextEdit作爲「顯示器」(可編輯爲false)。它顯示的文字是字跡包裝。現在我希望設置此文本框的高度,以便文本完全適合(同時還要考慮最大高度)。qtextedit - 調整大小以適合
基本上,佈局下面的小部件(在同一垂直佈局中)應儘可能多地佔用空間。
這怎麼能最容易實現?
當前基礎文本的大小可以通過
QTextEdit::document()->size();
可我相信,使用此,我們可以相應地調整小部件。
#include <QTextEdit>
#include <QApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextEdit te ("blah blah blah blah blah blah blah blah blah blah blah blah");
te.show();
cout << te.document()->size().height() << endl;
cout << te.document()->size().width() << endl;
cout << te.size().height() << endl;
cout << te.size().width() << endl;
// and you can resize then how do you like, e.g. :
te.resize(te.document()->size().width(),
te.document()->size().height() + 10);
return a.exec();
}
除非有一個QTextEdit
好需要的能力的東西特別是自動換一個QLabel
開啓後就會做你想要什麼。
只需在單詞邊界上標記wordwrap,也不會在數據太大時顯示滾動條。我開始使用標籤,但我需要兩個功能集似乎... – paul23 2012-02-29 22:40:19
那麼,'QLabel'不會工作:) – 2012-02-29 22:44:16
我發現一個非常穩定,簡單的解決方案,使用QFontMetrics
!
from PyQt4 import QtGui
text = ("The answer is QFontMetrics\n."
"\n"
"The layout system messes with the width that QTextEdit thinks it\n"
"needs to be. Instead, let's ignore the GUI entirely by using\n"
"QFontMetrics. This can tell us the size of our text\n"
"given a certain font, regardless of the GUI it which that text will be displayed.")
app = QtGui.QApplication([])
textEdit = QtGui.QPlainTextEdit()
textEdit.setPlainText(text)
textEdit.setLineWrapMode(True) # not necessary, but proves the example
font = textEdit.document().defaultFont() # or another font if you change it
fontMetrics = QtGui.QFontMetrics(font) # a QFontMetrics based on our font
textSize = fontMetrics.size(0, text)
textWidth = textSize.width() + 30 # constant may need to be tweaked
textHeight = textSize.height() + 30 # constant may need to be tweaked
textEdit.setMinimumSize(textWidth, textHeight) # good if you want to insert this into a layout
textEdit.resize(textWidth, textHeight) # good if you want this to be standalone
textEdit.show()
app.exec_()
(請原諒我,我知道你的問題是關於C++和我使用Python,但在Qt
他們幾乎同樣的事情反正)。
說到Python,我發現.setFixedWidth(your_width_integer)
和.setFixedSize(your_width, your_height)
相當有用。不確定C是否具有類似的小部件屬性。
就我而言,我將QLabel放在QScrollArea中。如果你非常熱衷,你可以將兩者結合起來並製作你自己的小部件。
不能在QT庫找到qtextbox – 2012-02-29 21:19:16
意味的QTextEdit,固定(帶鏈接) – paul23 2012-02-29 21:24:11
如果你把其他的QTextEdit裏面QScrollArea(設置最大高度),你可以使用我給有相同的代碼:HTTP://計算器.com/questions/7301785/react-on-the-resizing-a-qmainwindow-for-adjust-widgets-size – alexisdm 2012-03-01 01:40:26