已经有类似的问题被问过,但没有得到清晰的答案,所以我要再问一遍。假设我们有一个QMainWindow和一个内部的QScrollArea。我在程序中调整了QScrollArea的大小,希望窗口也能相应调整大小。 下面的代码几乎可以正确地工作:当新图片大于旧图片时,窗口大小会增加。然而,当新图片比旧图片小时,窗口不会变小,而是只有QScrollArea变小,导致QScrollArea与其他元素(标签、按钮)之间出现了空隙。
class PictureDialog : public QMainWindow {
Q_OBJECT
public:
PictureDialog() : QMainWindow() {
QWidget* canvas = new QWidget(this);
setCentralWidget(canvas);
QVBoxLayout* layout = new QVBoxLayout(canvas);
imageLabel = new QLabel(" ");
imageLabel->setStyleSheet("QLabel { background-color : white; color : black; }");
scrollArea = new QScrollArea(this);
scrollArea->resize(300, 300);
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageLabel);
layout->addWidget(scrollArea);
imgnamelabel = new QLabel(tr("Picture: "), this);
layout->addWidget(imgnamelabel);
QHBoxLayout *hlayout = new QHBoxLayout();
layout->addLayout(hlayout);
yesButton = new QPushButton(QPixmap(":pics/yes.png"), QString::null, this);
yesButton->setShortcut(Qt::Key_Plus);
yesButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
hlayout->addWidget(yesButton);
noButton = new QPushButton(QPixmap(":pics/no.png"), QString::null, this);
noButton->setShortcut(Qt::Key_Minus);
noButton->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
hlayout->addWidget(noButton);
hlayout->addStretch();
connect(yesButton, SIGNAL(clicked()), SLOT(hide()));
connect(noButton, SIGNAL(clicked()), SLOT(hide()));
}
void setPicture(QString imagePath, bool showNo) {
imgnamelabel->setText(tr("Picture: ") + imagePath);
if (!QFile::exists(imagePath)) {
imageLabel->setText(tr("Picture file not found: ") + imagePath);
imageLabel->resize(imageLabel->fontMetrics().boundingRect(imageLabel->text()).width(),
imageLabel->fontMetrics().boundingRect(imageLabel->text()).height());
} else {
QImage image(imagePath);
if (image.isNull()) {
imageLabel->setText(tr("Failed to open picture file: ") + imagePath);
imageLabel->resize(imageLabel->fontMetrics().boundingRect(imageLabel->text()).width(),
imageLabel->fontMetrics().boundingRect(imageLabel->text()).height());
} else {
imageLabel->setPixmap(QPixmap::fromImage(image));
imageLabel->resize(image.width(), image.height());
}
}
scrollArea->setFixedSize(mini(imageLabel->width() + 20, QApplication::desktop()->screenGeometry().width() * 8 / 10),
mini(imageLabel->height() + 20, QApplication::desktop()->screenGeometry().height() * 8 / 10));
adjustSize();
updateGeometry();
if (showNo)
noButton->setEnabled(true);
else
noButton->setEnabled(false);
}
QPushButton *yesButton, *noButton;
private:
QLabel *imageLabel;
QLabel *imgnamelabel;
QScrollArea* scrollArea;
};