类似的问题已经问过了,但没有给出明确的答案,所以我再问一次。假设我们有一个 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;
};