【发布时间】:2015-07-13 21:30:33
【问题描述】:
我正在尝试使用 lineedit 和按钮制作一个小部件。如果单击该按钮,它应该打开一个文件对话框,我可以在其中选择一个文件。然后文件名应显示在 lineedit 中。这是我到目前为止得到的:
#include "widget_openimage.h"
#include <QFontMetrics>
Widget_openimage::Widget_openimage(QWidget *parent) : QWidget(parent) {
// horizontal layout
layout = new QHBoxLayout();
// linedit on the left which shows the path of the chosen file
lineedit = new QLineEdit();
lineedit->setReadOnly(true);
// pushbutton on the right to select the file
btn = new QPushButton("...");
btn->setFixedSize(20,20);
connect(btn, SIGNAL(clicked()), this, SLOT(btn_clicked()));
connect(lineedit, SIGNAL(textChanged(QString)), this, SLOT(resize_to_content()));
layout->addWidget(lineedit);
layout->addWidget(btn);
this->setLayout(layout);
}
void Widget_openimage::btn_clicked() {
QString filename = QFileDialog::getOpenFileName(this,tr("Open"), "", tr("Image Files (*.png *.jpg *.bmp));
if (filename.isEmpty())
return;
else {
lineedit->setText(filename);
}
}
void Widget_openimage::resize_to_content() {
QString text = lineedit->text();
QFontMetrics fm = lineedit->fontMetrics();
int width = fm.boundingRect(text).width();
lineedit->resize(width, lineedit->height());
}
按钮的openfile函数工作正常,并且在lineedit中也显示了正确的路径。但是调整大小不起作用。谁能帮帮我?
【问题讨论】:
-
当你不调用它的
setText方法时,如何在 lineedit 中显示正确的路径?此外,您在错误的位置调用connect到textChanged(QString)信号 - 您应该在构造函数中调用它。 -
对不起,我的错,setText当然在我的原始代码中,我只是在写问题时忘记了它。现在我将 textChanged-connect 移到另一个之后的构造函数中。但它仍然不起作用......