前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qt 之自定义搜索框

Qt 之自定义搜索框

作者头像
全栈程序员站长
发布2022-09-14 10:15:58
7910
发布2022-09-14 10:15:58
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

简述

关于搜索框,大家都经常接触。例如:浏览器搜索、Windows资源管理器搜索等。

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

当然,这些对于Qt实现来说毫无压力,只要思路清晰,分分钟搞定。

  • 方案一:调用QLineEdit现有接口
    • void addAction(QAction * action, ActionPosition position) 在QLineEdit的前/后添加部件,ActionPosition表示部件所在方位。
    • QAction * addAction(const QIcon & icon, ActionPosition position) 重载函数。

枚举:QLineEdit::ActionPosition

常量

描述

QLineEdit::LeadingPosition

0

当使用布局方向Qt::LeftToRight时,部件显示在文本左侧,使用Qt::RightToLeft则显示在右侧。

QLineEdit::TrailingPosition

1

当使用布局方向Qt::LeftToRight时,部件显示在文本右侧,使用Qt::RightToLeft则显示在左侧。

  • 方案二:自定义(可以实现任何组合)

下面,我们来针对自定义进行讲解。

| 版权声明:一去、二三里,未经博主允许不得转载。

效果

这里写图片描述
这里写图片描述

细节分析

实现细节需要如下步骤:

  1. 组合实现,输入框+按钮
  2. 事件关联
  3. 获取输入文本,进行文本搜索

为了更人性、易用,这里有一些细节需要注意:

  1. 输入框的文本不能处于按钮之下
  2. 输入框无文本时必须给与友好性提示
  3. 按钮无文本描述,一般需要给予ToolTip提示
  4. 按钮样式-正常、滑过、按下,以及鼠标滑过鼠标样式手型,

这些都想清楚了,我们就能快速实现一个搜索框了。

Coding

搜索框实现

代码语言:javascript
复制
m_pSearchLineEdit = new QLineEdit();
QPushButton *pSearchButton = new QPushButton(this);

pSearchButton->setCursor(Qt::PointingHandCursor);
pSearchButton->setFixedSize(22, 22);
pSearchButton->setToolTip(QStringLiteral("搜索"));
pSearchButton->setStyleSheet("QPushButton{border-image:url(:/images/icon_search_normal); background:transparent;} \ QPushButton:hover{border-image:url(:/images/icon_search_hover)} \ QPushButton:pressed{border-image:url(:/images/icon_search_press)}");

//防止文本框输入内容位于按钮之下
QMargins margins = m_pSearchLineEdit->textMargins();
m_pSearchLineEdit->setTextMargins(margins.left(), margins.top(), pSearchButton->width(), margins.bottom());
m_pSearchLineEdit->setPlaceholderText(QStringLiteral("请输入搜索内容"));

QHBoxLayout *pSearchLayout = new QHBoxLayout();
pSearchLayout->addStretch();
pSearchLayout->addWidget(pSearchButton);
pSearchLayout->setSpacing(0);
pSearchLayout->setContentsMargins(0, 0, 0, 0);
m_pSearchLineEdit->setLayout(pSearchLayout);

connect(pSearchButton, SIGNAL(clicked(bool)), this, SLOT(search()));

槽函数实现

代码语言:javascript
复制
void Widget::search()
{
    QString strText = m_pSearchLineEdit->text();
    if (!strText.isEmpty())
    {
        QMessageBox::information(this, QStringLiteral("搜索"), QStringLiteral("搜索内容为%1").arg(strText));
    }
}

源码下载

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/158580.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年7月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简述
  • 效果
  • 细节分析
  • Coding
  • 源码下载
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档