zoukankan      html  css  js  c++  java
  • QT 在QTabWidget中设置一些调色板

    这次所做的项目中需要用到如下功能,点击tableWidget中的子项,将会弹出颜色选值对话框,实现子项的改变,如下图所示:

    1、首先,将自己定制的调色板放入tableWidget中

    for (int i = 0; i < 3; i++)
    {
    	for (int j = 0; j < 3; j++)
    	{
    		myPushButton = new MyQPushButton(this);
    		ui.tableWidget->setCellWidget(i, j, myPushButton); //插入第i行,j列   
    	}
    }
        
    

    2、头文件

    #pragma once
    
    #include <QObject>
    #include <QPushButton>
    #include <QColorDialog>
    #include <QMouseEvent>
    class MyQPushButton : public QPushButton    //公有继承QPushButton
    {
        Q_OBJECT
    
    public:
        MyQPushButton(QWidget *parent);
        ~MyQPushButton();
      
    void setColor();//设置随机颜色   void setColor(QColor color);//设置特定颜色   QColor getColor() const;//获取颜色 private slots: void choiceColor(void); //方法一,通过信号与槽连接 protected: void mousePressEvent(QMouseEvent *event);  //方法二、通过重写鼠标按下事件 };

    3、源文件

    #include "MyQPushButton.h"

    MyQPushButton::MyQPushButton(QWidget *parent): QPushButton(parent) {   //connect(this, SIGNAL(clicked()), this, SLOT(choiceColor(void)));    //方法1   /*下面两行代码必须有,否则效果会有差异*/   setAutoFillBackground(true);  //设置自动填充背景   setFlat(true);  //设置成平面 } MyQPushButton::~MyQPushButton() { } /*点击本身响应的槽函数*/ void MyQPushButton::choiceColor(void) {   QColor color = QColorDialog::getColor(Qt::white, this);  //调出颜色选择器对话框   QPalette pal;  //此类包含每个小部件状态的颜色组   pal.setColor(QPalette::Button, color);  //QPalette::Button,  ColorRole enum定义了当前gui中使用的不同符号颜色角色。   setPalette(pal); } /*鼠标按下事件*/ void MyQPushButton::mousePressEvent(QMouseEvent *event) {   if (event->button() == Qt::LeftButton)   {   QPalette pal;   pal.setColor(QPalette::Button, QColorDialog::getColor());   this->setPalette(pal);   } } /*设置随机颜色*/  void MyQPushButton::setColor() { QColor color(rand() % 256, rand() % 256, rand() % 256);//产生一组随机的rgb值 QPalette pal; pal.setColor(QPalette::Button, color); setPalette(pal); } /*设置给定的颜色*/ void MyQPushButton::setColor(QColor color) { QPalette pal; pal.setColor(QPalette::Button, color); setPalette(pal); } /*获取当前颜色*/ QColor MyQPushButton::getColor() const { return this->palette().color(QPalette::Button); }
    4、获取当前按钮的颜色。
    QColor theColor=((MyQPushButton*)ui.tableWidget->cellWidget(i, j))->palette().color(QPalette::Button);//cellWidget(i, j)的返回值是QWidget*,所以一定要注意使用MyQPushButton*进行类的强制转化(不能使用MyQPushButton)。
    补充:获取颜色列表,可参考:https://blog.csdn.net/rl529014/article/details/51589096
    坚持成就伟大
  • 相关阅读:
    FineReport 子窗口刷新父页面
    Swagger rest API 描述
    maven properties 动态转换
    elasticsearch postman操作
    学习网站
    python | 干货:VSCode 13款插件和8个快捷键,工作效率提升10倍
    python | 5大SQL数据清洗方法
    python | 阿里云发短信教程详细(2) -Python3
    python | 阿里云短信发送服务
    python | Linux各目录及每个目录的详细介绍
  • 原文地址:https://www.cnblogs.com/xian-yongchao/p/9579939.html
Copyright © 2011-2022 走看看