提要
自定义行编辑器,点击后弹出颜色选择对话框,选择喜欢的颜色,确认后在行编辑器加载选中的颜色。
效果
选中某一个颜色后,行编辑器中加载所选的颜色。
示例
mylineedit.h
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QWidget>
#include <QLineEdit>
/******类功能描述:自定义行编辑器,可加载颜色*****/
class myLineEdit : public QLineEdit
{
Q_OBJECT
public:
myLineEdit(QWidget *parent = nullptr);
~myLineEdit();
void setBackgroundColor(QColor &color);//设置颜色
QColor getBackgroundColor();//获取设置的颜色
protected:
void paintEvent(QPaintEvent *event);//绘制编辑框的背景色
void mousePressEvent(QMouseEvent *event);//鼠标点击出现颜色对话框
private:
QColor m_color;//保存行编辑器的背景色
};
#endif // MYLINEEDIT_H
mylineedit.cpp
#include "mylineedit.h"
#include <QMouseEvent>
#include <QColorDialog>
#include <QFontDialog>
myLineEdit::myLineEdit(QWidget *parent)
:QLineEdit(parent)
{
m_color = QColor(255,170,127,255);
setReadOnly(true);//设置不可编辑
}
myLineEdit::~myLineEdit()
{
}
void myLineEdit::setBackgroundColor(QColor &color)
{
m_color = color;
update();
}
QColor myLineEdit::getBackgroundColor()
{
return m_color;
}
void myLineEdit::paintEvent(QPaintEvent *event)
{
QPalette pal;
pal.setBrush(QPalette::Base,QColor(m_color));
setPalette(pal);
QLineEdit::paintEvent(event);
}
void myLineEdit::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton){
QColorDialog colorDlg(this);
colorDlg.setFixedSize(600,500);
colorDlg.setWindowTitle("颜色选择对话框");
colorDlg.setCurrentColor(QColor(170,0,0,255));
if(colorDlg.exec() == QColorDialog::Accepted){
QColor color = colorDlg.currentColor();
setBackgroundColor(color);
}
}
QLineEdit::mousePressEvent(event);
}
以上便可以实现行编辑器用来加载颜色,使用时将该类的头文件和源文件拷进到项目中,包含该类的头文件,在ui文件中拖入QLineEdit控件,在控件上右键,选择提升为,弹出提升的窗口部件对话框,填写提升的类名称时,将类名myLineEdit直接拷贝到提升的类名称的后面的编辑框中,会自动加载下面的头文件后面的内容,勾选全局包含时,整个程序中的QLineEdit控件都可以使用该类来提升,点击添加按钮,然后点击提升按钮。原本的行编辑器就变为了自定义的行编辑器。