Adding pictures on the left side of lineEdit is often used in login input, search input and other scenarios, here is a record
1. How to add
//对lineEdit左侧嵌入图片
QAction *action = new QAction(this);
action->setIcon(QIcon(":/QQ_Image_touming/email.png"));
ui->lineEdit->addAction(action,QLineEdit::LeadingPosition);
//这段代码中,我们创建了一个QAction并设置其图标,然后通过addAction()方法将该QAction添加到QLineEdit控件的左侧。
//请注意,第二个参数指定添加的位置,这里我们使用了QLineEdit::LeadingPosition以在最左侧添加图像
Effect:
Before setting:
After setting:
2, How to achieve image scaling (generally not used, it will automatically scale to the width of the lineEdit when the image is embedded)
//实现缩放
// 创建QAction并设置图标
QAction *action2 = new QAction(this);
action->setIcon(QIcon(":/QQ_Image_touming/email.png"));
// 获取QPixmap对象,并进行缩放操作(这里将图像增大为50x50)
QPixmap pixmap3 = action->icon().pixmap(QSize(80, 80)).scaled(QSize(50, 50), Qt::KeepAspectRatio, Qt::SmoothTransformation);
// 将缩放后的图像重新设置为QIcon
action->setIcon(QIcon(pixmap3));
// 将QAction添加到QLineEdit控件的左侧位置
ui->lineEdit->addAction(action, QLineEdit::LeadingPosition);