这个是运行结果
#ifndef CUSTOMCELLWIDGET_H
#define CUSTOMCELLWIDGET_H
#include <QWidget>
#include <QColor>
class QLabel;
class QPushButton;
class CustomCellWidget : public QWidget
{
Q_OBJECT
public:
CustomCellWidget(const QString& text, const QColor& color, QWidget* parent = nullptr);
// New methods to modify color and text
void setColor(const QColor& color);
void setText(const QString& text);
signals:
void menuClicked(const QString& text);
private slots:
void onMenuClicked();
private:
QString m_text;
QColor m_color;
QLabel* m_colorLabel;
QLabel* m_textLabel;
};
#endif // CUSTOMCELLWIDGET_H
#include "CustomCellWidget.h"
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
CustomCellWidget::CustomCellWidget(const QString& text, const QColor& color, QWidget* parent)
: QWidget(parent), m_text(text), m_color(color)
{
QHBoxLayout* mainLayout = new QHBoxLayout(this);
mainLayout->setContentsMargins(10, 5, 10, 5); // 增加左右边距
mainLayout->setSpacing(0);
// 添加左侧弹性空间
mainLayout->addStretch(1);
// 创建一个水平布局来容纳颜色标签和文本标签
QHBoxLayout* labelLayout = new QHBoxLayout();
labelLayout->setSpacing(5);
labelLayout->setAlignment(Qt::AlignCenter);
m_colorLabel = new QLabel(this);
m_colorLabel->setFixedSize(5, 5);
setColor(color);
labelLayout->addWidget(m_colorLabel);
m_textLabel = new QLabel(text, this);
// 设置字体
QFont font = m_textLabel->font();
font.setPointSize(10);
font.setBold(true);
m_textLabel->setFont(font);
labelLayout->addWidget(m_textLabel);
// 将水平布局添加到主布局中
mainLayout->addLayout(labelLayout);
// 添加右侧弹性空间
mainLayout->addStretch(1);
// 设置整个widget的大小策略,使其能够在垂直和水平方向上扩展
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void CustomCellWidget::onMenuClicked()
{
emit menuClicked(m_text);
}
void CustomCellWidget::setColor(const QColor& color)
{
m_color = color;
m_colorLabel->setStyleSheet(QString("background-color: %1; border-radius: 3px;").arg(color.name()));
}
void CustomCellWidget::setText(const QString& text)
{
m_text = text;
m_textLabel->setText(text);
}
//
#include <QApplication>
#include <QTableWidget>
#include <QHeaderView>
#include <QDebug>
#include "CustomCellWidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTableWidget table;
table.setColumnCount(1);
table.setRowCount(5);
table.horizontalHeader()->setStretchLastSection(true);
table.verticalHeader()->setVisible(false);
table.setShowGrid(false);
QStringList statuses = {"状态一", "状态二", "状态三", "状态四", "状态五"};
QList<QColor> colors = {Qt::blue, Qt::green, Qt::yellow, Qt::red, Qt::gray};
for (int i = 0; i < 5; ++i) {
CustomCellWidget* widget = new CustomCellWidget(statuses[i], colors[i]);
table.setCellWidget(i, 0, widget);
}
table.setColumnWidth(0, 60);
table.resize(300, 200);
table.show();
return a.exec();
}