写在前面
这里自定义一个搜索控件,通过自定义LineEdit的textChange信号,搜索指定内容,并以QCheckBox的方式显示在QListWidget中。
开发版本
Qt: 5.15.2
Qt: Creator10.0.2
编译环境:msvc2019_64bit release
效果
代码
自定义LineEdit,带前缀图标。
//MLineEdit.h
#ifndef MLINEEDIT_H
#define MLINEEDIT_H
#include <QLineEdit>
#include <QHBoxLayout>
class MLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit MLineEdit(QWidget *parent = nullptr);
signals:
private:
QHBoxLayout* layout;
};
#endif // MLINEEDIT_H
//MLineEdit.cpp
#include "mlineedit.h"
#include <QLabel>
#include <QDebug>
MLineEdit::MLineEdit(QWidget *parent)
: QLineEdit{parent}
{
layout = new QHBoxLayout(this);
QLabel* prefixIcon = new QLabel(this);
QPixmap pix(":/icons/search.svg");
prefixIcon->setPixmap(pix);
prefixIcon->setFixedSize(pix.size());
layout->addWidget(prefixIcon);
layout->setContentsMargins(1, 1, 1, 1);
layout->addStretch();
layout->setDirection(QBoxLayout::LeftToRight);
qDebug() << font();
setFont(QFont("SimSun", 15));
setTextMargins(prefixIcon->width(), 1, 1, 1);
QString qss = QString("QLineEdit{border:1px solid gray;border-radius:10px;}");
setStyleSheet(qss);
}
应用实现:
//MyWidgets.h
#ifndef MYWIDGETS_H
#define MYWIDGETS_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class MyWidgets; }
QT_END_NAMESPACE
class MyWidgets : public QWidget
{
Q_OBJECT
public:
MyWidgets(QWidget *parent = nullptr);
~MyWidgets();
public slots:
void textChangeSlot(const QString& text);
private:
Ui::MyWidgets *ui;
QStringList qlCheck;
};
#endif // MYWIDGETS_H
//MyWidgets.cpp
#include "mywidgets.h"
#include "ui_mywidgets.h"
#include <QPushButton>
#include <QIcon>
#include <QCheckBox>
#include <QDebug>
#include <QListWidgetItem>
#include "mlineedit.h"
MyWidgets::MyWidgets(QWidget *parent)
: QWidget(parent)
, ui(new Ui::MyWidgets)
{
ui->setupUi(this);
qlCheck << tr("whatsApp") << tr("weChat") << tr("QQ") << tr("Telegram") << tr("twitter");
connect(ui->lineEdit, &QLineEdit::textChanged, this, &MyWidgets::textChangeSlot);
}
MyWidgets::~MyWidgets()
{
delete ui;
}
void MyWidgets::textChangeSlot(const QString& text)
{
QString qsInput = ui->lineEdit->text();
qDebug() << qsInput;
ui->listWidget->clear();
if (qsInput.isEmpty())
{
return;
}
for (QString qs : qlCheck)
{
if (qs.contains(qsInput, Qt::CaseInsensitive))
{
QCheckBox* checkBox = new QCheckBox(this);
checkBox->setText(qs);
QListWidgetItem* listItem = new QListWidgetItem();
ui->listWidget->addItem(listItem);
ui->listWidget->setItemWidget(listItem, checkBox);
}
}
}
ui布局及完整代码可见github仓库:https://github.com/SNAKEpg12138/SearchWidget
总结
使用样式表实现带前缀图标的LineEdit,并通过一个简单的搜索控件应用。