我正在嘗試使用lineedit和按鈕做一個小部件。如果按鈕被點擊,它應該打開一個filedialog,我可以選擇一個文件。文件名應該顯示在lineedit中。這是我到目前爲止:qlineedit自動調整大小到內容
#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中。但調整大小不起作用。任何人都可以借我一隻手嗎?
如何在正確的道路來顯示它的lineedit,當你不把它叫做是'setText'方法嗎?還有你調用'connect'到'textChanged(QString)'信號在錯誤的地方 - 你應該在構造函數中調用它 – Amartel
抱歉,我的錯,setText當然是在我的原始代碼中,我只是在寫這個問題時忘了它。我將textChanged-connect移入構造函數中之一。但它仍然無法正常工作... – yangsunny