Qt 调整小部件的QMainWindow的大小时作出反应';s码
如何对调整Qt 调整小部件的QMainWindow的大小时作出反应';s码,qt,resize,signals-slots,autosize,qmainwindow,Qt,Resize,Signals Slots,Autosize,Qmainwindow,如何对调整QMainWindow的大小作出反应?我在qscrollara中有QTextBrowsers,我在创建它们时会根据内容的大小调整它们(唯一应该滚动的是qscrollara) 现在一切正常,但如果我调整main窗口的大小,则不会更改QTextBrowsers的高度,因为不会触发回流功能 您有没有更好的办法调整QTextBrowser以适应其内容?我目前的代码是: void RenderFrame::adjustTextBrowser(QTextBrowser* e) const {
QMainWindow
的大小作出反应?我在qscrollara
中有QTextBrowsers
,我在创建它们时会根据内容的大小调整它们(唯一应该滚动的是qscrollara
)
现在一切正常,但如果我调整main窗口的大小,则不会更改QTextBrowsers
的高度,因为不会触发回流功能
您有没有更好的办法调整QTextBrowser
以适应其内容?我目前的代码是:
void RenderFrame::adjustTextBrowser(QTextBrowser* e) const {
e->document()->setTextWidth(e->parentWidget()->width());
e->setMinimumHeight(e->document()->size().toSize().height());
e->setMaximumHeight(e->minimumHeight());
}
parentWidget()
是必需的,因为在小部件上运行width()
总是返回100,而不管实际大小。如果只有文本或html,您可以使用QLabel
,因为它已经根据可用空间调整了大小。您必须使用:
label->setWordWrap(true);
label->setTextInteractionFlags(Qt::TextBrowserInteraction);
与QTextBrowser
具有几乎相同的行为
如果您真的想使用QTextBrowser
,可以尝试类似的方法(改编自QLabel
源代码):
类文本浏览器:公共QTextBrowser{
Q_对象
公众:
显式文本浏览器(QWidget*父级):QTextBrowser(父级){
//当大小发生变化时,应调用updateGeometry
//文档更改时,大小也会更改
连接(此,信号(textChanged()),插槽(onTextChanged());
QSizePolicy policy=sizePolicy();
//够明显吗?
policy.setHeightForWidth(true);
制定政策(政策);
}
整数高度宽度(整数宽度)常数{
int左、上、右、下;
getContentsMargins(左、上、右、下);
QSize页边距(左+右,上+下);
//由于处理真实文档似乎会导致无限递归,
//我们创建一个克隆来计算宽度
QScopedPointer tempDoc(document()->clone());
tempDoc->setTextWidth(width-margins.width());
返回qMax(tempDoc->size().toSize().height()+边距.height(),
最小高度();
}
专用插槽:
void onTextChanged(){
更新计量学();
}
};
调整小部件大小的标准方法是将它们放在适当配置的布局中。但无法使QtextBrowser
自动调整到不需要滚动条的最小可能大小
class TextBrowser : public QTextBrowser {
Q_OBJECT
public:
explicit TextBrowser(QWidget *parent) : QTextBrowser(parent) {
// updateGeometry should be called whenever the size changes
// and the size changes when the document changes
connect(this, SIGNAL(textChanged()), SLOT(onTextChanged()));
QSizePolicy policy = sizePolicy();
// Obvious enough ?
policy.setHeightForWidth(true);
setSizePolicy(policy);
}
int heightForWidth(int width) const {
int left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
QSize margins(left + right, top + bottom);
// As working on the real document seems to cause infinite recursion,
// we create a clone to calculate the width
QScopedPointer<QTextDocument> tempDoc(document()->clone());
tempDoc->setTextWidth(width - margins.width());
return qMax(tempDoc->size().toSize().height() + margins.height(),
minimumHeight());
}
private slots:
void onTextChanged() {
updateGeometry();
}
};