简述:![](https://i-blog.csdnimg.cn/blog_migrate/e480265e918e30d3dc0b5bced3d07c26.gif)
QT实现自定义表情包,通过对(能够设置表情的行列数 , 表情的大小,表情的个数、最大行数等)
效果:
代码如下:
EmoticonsWidget主要实现表情包窗口。
EmoticonsWidget.cpp
#include "EmoticonsWidget.h"
#include "SmileyPack.h"
#include <QFile>
#include <QGridLayout>
#include <QLayout>
#include <QMouseEvent>
#include <QPushButton>
#include <QRadioButton>
#include <QDebug>
#include <math.h>
QString getStylesheet(const QString& filename)
{
QFile file(filename);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
qWarning() << "Stylesheet " << filename << " not found";
return QString();
}
return file.readAll();
}
EmoticonsWidget::EmoticonsWidget(QWidget* parent)
: QMenu(parent)
{
setStyleSheet(getStylesheet(":/ui/EmoticonWidget.css"));
setLayout(&layout);
layout.addWidget(&stack);
QWidget* pageButtonsContainer = new QWidget;
QHBoxLayout* buttonLayout = new QHBoxLayout;
pageButtonsContainer->setLayout(buttonLayout);
layout.addWidget(pageButtonsContainer);
const int maxCols = 8;
const int maxRows = 8;
const int itemsPerPage = maxRows * maxCols;
const QList<QStringList>& emoticons = SmileyPack::getInstance().getEmoticons();
int itemCount = emoticons.size();
int pageCount = ceil(float(itemCount) / float(itemsPerPage));
int currPage = 0;
int currItem = 0;
int row = 0;
int col = 0;
// 配置表情大小
const int px = 40;
const QSize size(px, px);
// 创建页面
buttonLayout->addStretch();
for (int i = 0; i < pageCount; ++i) {
QGridLayout* pageLayout = new QGridLayout;
pageLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding),
maxRows, 0);
pageLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum), 0,
maxCols);
QWidget* page = new QWidget;
page->setLayout(pageLayout);
stack.addWidget(page);
// 只有当页面超过1个时才需要页面按钮
if (pageCount > 1) {
QRadioButton* pageButton = new QRadioButton;
pageButton->setProperty("pageIndex", i);
pageButton->setCursor(Qt::PointingHandCursor);
pageButton->setChecked(i == 0);
buttonLayout->addWidget(pageButton);
connect(pageButton, &QRadioButton::clicked, this, &EmoticonsWidget::onPageButtonClicked);
}
}
buttonLayout->addStretch();
SmileyPack& smileyPack = SmileyPack::getInstance();
for (const QStringList& set : emoticons) {
QPushButton* button = new QPushButton;
std::shared_ptr<QIcon> icon = smileyPack.getAsIcon(set[0]);
emoticonsIcons.append(icon);
button->setIcon(icon->pixmap(size));
button->setToolTip(set.join(" "));
button->setProperty("sequence", set[0]);
button->setCursor(Qt::PointingHandCursor);
button->setFlat(true);
button->setIconSize(size);
button->setFixedSize(size);
connect(button, &QPushButton::clicked, this, &EmoticonsWidget::onSmileyClicked);
qobject_cast