Qt 实现聊天软件中自定义表情包(随笔记录)

 

简述:Qt 实现聊天软件中自定义表情包(随笔记录)_第1张图片

QT实现自定义表情包,通过对(能够设置表情的行列数 , 表情的大小,表情的个数、最大行数等)

效果:

Qt 实现聊天软件中自定义表情包(随笔记录)_第2张图片

                           

Qt 实现聊天软件中自定义表情包(随笔记录)_第3张图片

代码如下:

EmoticonsWidget主要实现表情包窗口。

EmoticonsWidget.cpp

#include "EmoticonsWidget.h"
#include "SmileyPack.h"

#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 

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& 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 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);
 

你可能感兴趣的:(qt,c++)