一句话,上代码:
1.头文件:
#ifndef COLORSELECTWINDOW_H
#define COLORSELECTWINDOW_H
#include <QWidget>
#include <QWidget>
#include<QComboBox>
#include<QFrame>
#include <QLabel>
#include <QTextEdit>
#include <QPushButton>
#include <QToolButton>
#include <QLineEdit>
#include <QColorDialog>
namespace Ui {
class ColorSelectWindow;
}
class ColorSelectWindow : public QWidget
{
Q_OBJECT
public:
explicit ColorSelectWindow(QWidget *parent = nullptr);
private slots:
void btnClickedFun();
public:
QColor getColor()
{
return m_color;
}
void setColor(const QColor& color)
{
if( color.isValid() )
{
m_color = color;
m_label->setStyleSheet( QString("background-color:%1").arg( color.name() ) );
m_lineEdit->setText( color.name() );
}
}
private:
void uier();
void initialize();
QColor m_color;
QLabel* m_label;
QLineEdit* m_lineEdit;
QToolButton* m_button;
public:
~ColorSelectWindow();
private:
Ui::ColorSelectWindow *ui;
};
#endif // COLORSELECTWINDOW_H
2、源文件:
#include "ColorSelectWindow.h"
#include "ui_ColorSelectWindow.h"
#include <QPalette>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QStringList>
#include <QColor>
#include <QPixmap>
#include <QSpinBox>
#include <QTextEdit>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#pragma execution_character_set("utf-8")
ColorSelectWindow::ColorSelectWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::ColorSelectWindow)
{
ui->setupUi(this);
this->uier();
this->initialize();
}
void ColorSelectWindow::uier()
{
m_label = new QLabel();
m_lineEdit = new QLineEdit();
m_button = new QToolButton();
QHBoxLayout* layout = new QHBoxLayout(this);
layout->setMargin(20);
layout->addWidget( m_label );
layout->setSpacing(10);
layout->addWidget(m_lineEdit,1);
layout->setSpacing(10);
layout->addWidget(m_button);
this->setLayout( layout );
this->setAutoFillBackground(true);
QPalette palete;
palete.setColor(QPalette::Background,Qt::white);
this->setPalette(palete);
}
void ColorSelectWindow::initialize()
{
m_color = Qt::green;
m_label->setFixedWidth(120);
m_label->setFixedHeight(50);
m_label->setStyleSheet( QString("background-color:%1").arg( m_color.name() ) );
m_lineEdit->setText( m_color.name() );
m_lineEdit->setFocusPolicy( Qt::NoFocus);
m_button->setText("...");
connect( m_button,SIGNAL( clicked() ),this,SLOT( btnClickedFun() ) );
}
void ColorSelectWindow::btnClickedFun()
{
QColor color = QColorDialog::getColor( m_color );
if(color.isValid())
{
m_color=color;
m_label->setStyleSheet(QString("background-color:%1").arg(m_color.name()));
m_lineEdit->setText(m_color.name());
}
}
ColorSelectWindow::~ColorSelectWindow()
{
delete ui;
}
效果如下图所示: