I'm trying to do a small widget with a lineedit and a pushbutton. If the button is clicked, it should open a filedialog where I can select a file. The file name should then showed in the lineedit. Here is what i got so far:
#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());
}
the openfile function of the button works fine, and the right path is shown in the lineedit too. however the resize doesnt work. can anyone lend me a hand?
setText
method? Also you callconnect
totextChanged(QString)
signal in the wrong place - you should call it in constructor. – Dilley