我正在尝试创建一个带有LineEdit和PushButton的小部件。如果单击按钮,它应该打开一个FileDialog,让我选择一个文件。然后文件名应该显示在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)
信号 - 你应该在构造函数中调用它。 - Amartel