Как изменить цвет groupbox

In C#.NET I am trying to programmatically change the color of the border in a group box. Update: This question was asked when I was working on a winforms system before we switched to .NET.

FWIW, this is the implementation I used. It’s a child of GroupBox but allows setting not only the BorderColor, but also the thickness of the border and the radius of the rounded corners. Also, you can set the amount of indent you want for the GroupBox label, and using a negative indent indents from the right side.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace BorderedGroupBox
{
    public class BorderedGroupBox : GroupBox
    {
        private Color _borderColor = Color.Black;
        private int _borderWidth = 2;
        private int _borderRadius = 5;
        private int _textIndent = 10;

        public BorderedGroupBox() : base()
        {
            InitializeComponent();
            this.Paint += this.BorderedGroupBox_Paint;
        }

        public BorderedGroupBox(int width, float radius, Color color) : base()
        {
            this._borderWidth = Math.Max(1,width);
            this._borderColor = color;
            this._borderRadius = Math.Max(0,radius);
            InitializeComponent();
            this.Paint += this.BorderedGroupBox_Paint;
        }

        public Color BorderColor
        {
            get => this._borderColor;
            set
            {
                this._borderColor = value;
                DrawGroupBox();
            }
        }

        public int BorderWidth
        {
            get => this._borderWidth;
            set
            {
                if (value > 0)
                {
                    this._borderWidth = Math.Min(value, 10);
                    DrawGroupBox();
                }
            }
        }

        public int BorderRadius
        {
            get => this._borderRadius;
            set
            {   // Setting a radius of 0 produces square corners...
                if (value >= 0)
                {
                    this._borderRadius = value;
                    this.DrawGroupBox();
                }
            }
        }

        public int LabelIndent
        {
            get => this._textIndent;
            set
            {
                this._textIndent = value;
                this.DrawGroupBox();
            }
        }

        private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =>
            DrawGroupBox(e.Graphics);

        private void DrawGroupBox() =>
            this.DrawGroupBox(this.CreateGraphics());

        private void DrawGroupBox(Graphics g)
        {
            Brush textBrush = new SolidBrush(this.ForeColor);
            SizeF strSize = g.MeasureString(this.Text, this.Font);

            Brush borderBrush = new SolidBrush(this.BorderColor);
            Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);
            Rectangle rect = new Rectangle(this.ClientRectangle.X,
                                            this.ClientRectangle.Y + (int)(strSize.Height / 2),
                                            this.ClientRectangle.Width - 1,
                                            this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);

            Brush labelBrush = new SolidBrush(this.BackColor);

            // Clear text and border
            g.Clear(this.BackColor);

            // Drawing Border (added "Fix" from Jim Fell, Oct 6, '18)
            int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;
            int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;
            // NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height
            g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);

            // Draw text
            if (this.Text.Length > 0)
            {
                // Do some work to ensure we don't put the label outside
                // of the box, regardless of what value is assigned to the Indent:
                int width = (int)rect.Width, posX;
                posX = (this._textIndent < 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);
                posX = (posX < 0) ? rect.Width + posX - (int)strSize.Width : posX;
                g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);
                g.DrawString(this.Text, this.Font, textBrush, posX, 0);
            }
        }

        #region Component Designer generated code
        /// <summary>Required designer variable.</summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>Clean up any resources being used.</summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
                components.Dispose();

            base.Dispose(disposing);
        }

        /// <summary>Required method for Designer support - Don't modify!</summary>
        private void InitializeComponent() => components = new System.ComponentModel.Container();
        #endregion
    }
}

To make it work, you also have to extend the base Graphics class (Note: this is derived from some code I found on here once when I was trying to create a rounded-corners Panel control, but I can’t find the original post to link here):

static class GraphicsExtension
{
    private static GraphicsPath GenerateRoundedRectangle(
        this Graphics graphics,
        RectangleF rectangle,
        float radius)
    {
        float diameter;
        GraphicsPath path = new GraphicsPath();
        if (radius <= 0.0F)
        {
            path.AddRectangle(rectangle);
            path.CloseFigure();
            return path;
        }
        else
        {
            if (radius >= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)
                return graphics.GenerateCapsule(rectangle);
            diameter = radius * 2.0F;
            SizeF sizeF = new SizeF(diameter, diameter);
            RectangleF arc = new RectangleF(rectangle.Location, sizeF);
            path.AddArc(arc, 180, 90);
            arc.X = rectangle.Right - diameter;
            path.AddArc(arc, 270, 90);
            arc.Y = rectangle.Bottom - diameter;
            path.AddArc(arc, 0, 90);
            arc.X = rectangle.Left;
            path.AddArc(arc, 90, 90);
            path.CloseFigure();
        }
        return path;
    }

    private static GraphicsPath GenerateCapsule(
        this Graphics graphics,
        RectangleF baseRect)
    {
        float diameter;
        RectangleF arc;
        GraphicsPath path = new GraphicsPath();
        try
        {
            if (baseRect.Width > baseRect.Height)
            {
                diameter = baseRect.Height;
                SizeF sizeF = new SizeF(diameter, diameter);
                arc = new RectangleF(baseRect.Location, sizeF);
                path.AddArc(arc, 90, 180);
                arc.X = baseRect.Right - diameter;
                path.AddArc(arc, 270, 180);
            }
            else if (baseRect.Width < baseRect.Height)
            {
                diameter = baseRect.Width;
                SizeF sizeF = new SizeF(diameter, diameter);
                arc = new RectangleF(baseRect.Location, sizeF);
                path.AddArc(arc, 180, 180);
                arc.Y = baseRect.Bottom - diameter;
                path.AddArc(arc, 0, 180);
            }
            else path.AddEllipse(baseRect);
        }
        catch { path.AddEllipse(baseRect); }
        finally { path.CloseFigure(); }
        return path;
    }

    /// <summary>
    /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius
    /// for the arcs that make the rounded edges.
    /// </summary>
    /// <param name="brush">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>
    /// <param name="x">The x-coordinate of the upper-left corner of the rectangle to draw.</param>
    /// <param name="y">The y-coordinate of the upper-left corner of the rectangle to draw.</param>
    /// <param name="width">Width of the rectangle to draw.</param>
    /// <param name="height">Height of the rectangle to draw.</param>
    /// <param name="radius">The radius of the arc used for the rounded edges.</param>
    public static void DrawRoundedRectangle(
        this Graphics graphics,
        Pen pen,
        float x,
        float y,
        float width,
        float height,
        float radius)
    {
        RectangleF rectangle = new RectangleF(x, y, width, height);
        GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);
        SmoothingMode old = graphics.SmoothingMode;
        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        graphics.DrawPath(pen, path);
        graphics.SmoothingMode = old;
    }

    /// <summary>
    /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius
    /// for the arcs that make the rounded edges.
    /// </summary>
    /// <param name="brush">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>
    /// <param name="x">The x-coordinate of the upper-left corner of the rectangle to draw.</param>
    /// <param name="y">The y-coordinate of the upper-left corner of the rectangle to draw.</param>
    /// <param name="width">Width of the rectangle to draw.</param>
    /// <param name="height">Height of the rectangle to draw.</param>
    /// <param name="radius">The radius of the arc used for the rounded edges.</param>

    public static void DrawRoundedRectangle(
        this Graphics graphics,
        Pen pen,
        int x,
        int y,
        int width,
        int height,
        int radius)
    {
        graphics.DrawRoundedRectangle(
            pen,
            Convert.ToSingle(x),
            Convert.ToSingle(y),
            Convert.ToSingle(width),
            Convert.ToSingle(height),
            Convert.ToSingle(radius));
    }
}

  • Remove From My Forums
  • Question

  • Is there any way to change the border color of GroupBox ?

    Thnx!

Answers

  • Hi,Kapalic

    I’m not familiar with VB, but I’m able to translate it through a tool,here is the code translated:

    Public Class myGroupBox
        
    Inherits 
    GroupBoxPrivate borderColor As ColorPublic Sub New()
            
    MyBase.
    New
            Me
    .borderColor 
    Color.Black
        
    End Sub

            Public Property 

    BorderColor As Color
            
    Get
                Return Me
    .borderColor
            
    End Get
            Set
                Me
    .borderColor 
    value
            
    End Set
        End Property

            Protected Overrides Sub 

    OnPaint(ByVal As PaintEventArgs)
            
    Dim tSize As Size TextRenderer.MeasureText(Me.Text, Me
    .Font)
            
    Dim borderRect As Rectangle 
    e.ClipRectangle
            borderRect.Y 
    (borderRect.Y  _
                        + (tSize.Height / 
    2
    ))
            borderRect.Height 
    (borderRect.Height  _
                        — (tSize.Height / 
    2
    ))
            ControlPaint.DrawBorder(e.Graphics, borderRect, 
    Me
    .borderColor, ButtonBorderStyle.Solid)
            
    Dim textRect As Rectangle 
    e.ClipRectangle
            textRect.X 
    (textRect.X + 6
    )
            textRect.Width 
    tSize.Width
            textRect.Height 
    tSize.Height
            e.Graphics.FillRectangle(
    New SolidBrush(Me
    .BackColor), textRect)
            e.Graphics.DrawString(
    Me.Text, Me.Font, New SolidBrush(Me
    .ForeColor), textRect)
        
    End Sub
    End Class

  • Open the Solution Explorer, right click on the root,choose «Add»,then «Class», name the class as «myGroupBox»,and put my code in this class, rebuild your project, the you will see a «myGroupBox» control on your toolbox, it has a «BorderColor» property on the Misc group in the property view.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:

    1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:

    • Step 1: Create a windows form as shown in the below image:
      Visual Studio -> File -> New -> Project -> WindowsFormApp
    • Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:

    • Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:

      Output:

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:

    public virtual System.Drawing.Color BackColor { get; set; }

    Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:

    • Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.
      // Creating a GroupBox
      GroupBox gbox = new GroupBox(); 
      
    • Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.
      // Setting the background color
      gbox.BackColor = Color.LemonChiffon;
      
    • Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:
      // Adding groupbox in the form
      this.Controls.Add(gbox);
      
      and 
      
      // Adding this control 
      // to the GroupBox
      gbox.Controls.Add(c2);
      

      Example:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp45 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              GroupBox gbox = new GroupBox();

              gbox.Location = new Point(179, 145);

              gbox.Size = new Size(329, 94);

              gbox.Text = "Select Gender";

              gbox.Name = "Mybox";

              gbox.BackColor = Color.LemonChiffon;

              gbox.ForeColor = Color.Maroon;

              this.Controls.Add(gbox);

              CheckBox c1 = new CheckBox();

              c1.Location = new Point(40, 42);

              c1.Size = new Size(49, 20);

              c1.Text = "Male";

              gbox.Controls.Add(c1);

              CheckBox c2 = new CheckBox();

              c2.Location = new Point(183, 39);

              c2.Size = new Size(69, 20);

              c2.Text = "Female";

              gbox.Controls.Add(c2);

          }

      }

      }

      Output:

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In Windows form, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the background color of the GroupBox in the form using the BackColor Property. This property is an ambient property. You can set this property in two different ways:

    1. Design-Time: It is the easiest way to set the background color of the GroupBox as shown in the following steps:

    • Step 1: Create a windows form as shown in the below image:
      Visual Studio -> File -> New -> Project -> WindowsFormApp
    • Step 2: Next, drag and drop the GroupBox from the toolbox to the form as shown in the below image:

    • Step 3: After drag and drop you will go to the properties of the GroupBox and set the background color of the GroupBox as shown in the below image:

      Output:

    2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the background color of the GroupBox programmatically with the help of given syntax:

    public virtual System.Drawing.Color BackColor { get; set; }

    Here, Color indicates the background color of the GroupBox. The following steps show how to set the background color of the GroupBox dynamically:

    • Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.
      // Creating a GroupBox
      GroupBox gbox = new GroupBox(); 
      
    • Step 2: After creating GroupBox, set the BackColor property of the GroupBox provided by the GroupBox class.
      // Setting the background color
      gbox.BackColor = Color.LemonChiffon;
      
    • Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:
      // Adding groupbox in the form
      this.Controls.Add(gbox);
      
      and 
      
      // Adding this control 
      // to the GroupBox
      gbox.Controls.Add(c2);
      

      Example:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp45 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              GroupBox gbox = new GroupBox();

              gbox.Location = new Point(179, 145);

              gbox.Size = new Size(329, 94);

              gbox.Text = "Select Gender";

              gbox.Name = "Mybox";

              gbox.BackColor = Color.LemonChiffon;

              gbox.ForeColor = Color.Maroon;

              this.Controls.Add(gbox);

              CheckBox c1 = new CheckBox();

              c1.Location = new Point(40, 42);

              c1.Size = new Size(49, 20);

              c1.Text = "Male";

              gbox.Controls.Add(c1);

              CheckBox c2 = new CheckBox();

              c2.Location = new Point(183, 39);

              c2.Size = new Size(69, 20);

              c2.Text = "Female";

              gbox.Controls.Add(c2);

          }

      }

      }

      Output:

    RRS feed

    • Remove From My Forums
    • Вопрос

    • Hi,
          Am working in Visual C# Windows application. I need  to change the Border color of a Groupbox.How can i achieve it ?.

      Thanks in advance,

      Regards,
      Nataraj.C

      • Перемещено
        Peter Ritchie
        20 июня 2008 г. 13:42
        off-topic

    Ответы

    Все ответы

    • Hi
      Consider subclassing the GroupBox and manually draw the border and the title.
      See the following example:

      public class MyGroupBox : GroupBox{
      Color borderColor = Color.Red;
      // a fancy default color

      public MyGroupBox() {


      // to avoid flickering use double buffer


      SetStyle(ControlStyles.DoubleBuffer, true);


      // to force control to use OnPaint


      SetStyle(ControlStyles.UserPaint, true);

      }

      // assign the border color

      public Color BorderColor{


      get{



      return borderColor;

      }

      set{



      borderColor = value;

      }

      }

      // simple but incomplete OnPaint method, needs to draw the group box label

      // and other stuff as well

      protected override void OnPaint(PaintEventArgs e) {

      Graphics gr = e.Graphics;

      Rectangle r = new Rectangle(0, 0, Width — 1, Height — 1);


      using(Brush brush = new SolidBrush(BackColor)){


      using(Pen borderPen = new Pen(BorderColor)){

      gr.FillRectangle(brush, r);

      gr.DrawRectangle(borderPen, r);

      }

      }

    • And which forum would I goto to request that this feature is added to Visual Studio.  It is ridiculous that I have to right code to change the border color, especially when I can change the border on just about every other standard control, and I can change the background and foreground color on this control.  If nothing else, the control should change the border color to the foreground color instead of just the font foreground color.

      Thanks
      Evan Smith 

    28.12.2019C#

    В Windows Forms GroupBox — это контейнер, который содержит несколько элементов управления, и элементы управления связаны друг с другом. Или, другими словами, GroupBox представляет собой рамку, отображающую группу элементов управления с подходящим необязательным заголовком. Или GroupBox используется для классификации связанных элементов управления в группе. В GroupBox вы можете установить основной цвет GroupBox в форме, используя свойство ForeColor . Вы можете установить это свойство двумя различными способами:

    1. Время разработки: это самый простой способ установить цвет переднего плана GroupBox, как показано в следующих шагах:

    • Шаг 1: Создайте форму окна, как показано на рисунке ниже:
      Visual Studio -> Файл -> Создать -> Проект -> WindowsFormApp
    • Шаг 2: Затем перетащите GroupBox из панели инструментов в форму, как показано на рисунке ниже:

    • Шаг 3: После перетаскивания вы перейдете к свойствам GroupBox и установите цвет переднего плана GroupBox, как показано на рисунке ниже:

      Выход:

    2. Время выполнения: это немного сложнее, чем описанный выше метод. В этом методе вы можете программно установить цвет переднего плана GroupBox с помощью заданного синтаксиса:

    public virtual System.Drawing.Color ForeColor { get; set; }

    Здесь Color указывает основной цвет GroupBox. Следующие шаги показывают, как динамически установить цвет переднего плана GroupBox:

    • Шаг 1. Создание GroupBox с помощью конструктора GroupBox () предоставляется классом GroupBox.
      // Creating a GroupBox
      GroupBox gbox = new GroupBox(); 
      
    • Шаг 2. После создания GroupBox установите свойство ForeColor для GroupBox, предоставляемого классом GroupBox.
      // Setting the foreground color
      gbox.ForeColor = Color.Maroon;
      
    • Шаг 3. И, наконец, добавьте этот элемент управления GroupBox в форму, а также добавьте другие элементы управления в GroupBox, используя следующие операторы:
      // Adding groupbox in the form
      this.Controls.Add(gbox);
      
      and 
      
      // Adding this control to the GroupBox
      gbox.Controls.Add(c2);
      

      Пример:

      using System;

      using System.Collections.Generic;

      using System.ComponentModel;

      using System.Data;

      using System.Drawing;

      using System.Linq;

      using System.Text;

      using System.Threading.Tasks;

      using System.Windows.Forms;

      namespace WindowsFormsApp45 {

      public partial class Form1 : Form {

          public Form1()

          {

              InitializeComponent();

          }

          private void Form1_Load(object sender, EventArgs e)

          {

              GroupBox gbox = new GroupBox();

              gbox.Location = new Point(179, 145);

              gbox.Size = new Size(329, 94);

              gbox.Text = "Select Gender";

              gbox.Name = "Mybox";

              gbox.BackColor = Color.LemonChiffon;

              gbox.ForeColor = Color.Maroon;

              this.Controls.Add(gbox);

              CheckBox c1 = new CheckBox();

              c1.Location = new Point(40, 42);

              c1.Size = new Size(49, 20);

              c1.Text = "Male";

              gbox.Controls.Add(c1);

              CheckBox c2 = new CheckBox();

              c2.Location = new Point(183, 39);

              c2.Size = new Size(69, 20);

              c2.Text = "Female";

              gbox.Controls.Add(c2);

          }

      }
      }

      Выход:

    Рекомендуемые посты:

    • Как установить цвет фона GroupBox в C #?
    • Как установить основной цвет метки в C #?
    • Как установить цвет переднего плана ComboBox в C #?
    • Как установить основной цвет кнопки в C #?
    • Как установить основной цвет RadioButton в C #?
    • Как установить цвет переднего плана ListBox в C #?
    • Как установить цвет переднего плана FlowLayoutPanel в C #?
    • Как установить основной цвет для NumericUpDown в C #?
    • Как установить цвет переднего плана MaskedTextBox в C #?
    • Как установить цвет переднего плана RichTextBox в C #?
    • Как установить цвет переднего плана TextBox в C #?
    • Как установить цвет переднего плана CheckBox в C #?
    • C # | Как изменить основной цвет текста в консоли
    • Как установить имя GroupBox в C #?
    • Как установить видимость GroupBox в C #?

    Как установить цвет переднего плана GroupBox в C #?

    0.00 (0%) 0 votes

    Автор Тема: Как изменить цвет QGroupBox?  (Прочитано 10116 раз)
    zzzseregazzz

    Гость


    Добрый день.
    На форме (Qt 4.4.3) есть QGroupBox ui.gb, который надо выделить при щелчке мышью.
    Такой код не работает!

    C++ (Qt)

    QPalette p = ui.gb->palette();
    p.setBrush(ui.gb->backgroundRole(), QBrush(Qt::red));
    ui.gb->setPalette(p);

    Единственный способ, который сработал — создать наследника QGroupBox , и в paintEvent рисовать прямоугольник. Но во первых он выходит за рамку, во вторых получается задать только жестко заданный цвет. Переменная-член класса с цветом не учитывается. В отладчике увидел, что в paintEvent почему-то другой this по сравнению с setColor.

    C++ (Qt)

    void MyGroupBox::paintEvent(QPaintEvent* e)
    {
    QPainter p;
    p.begin(this);
    p.setBrush(color);//не работает
    p.setPen(color);//не работает
    p.setBrush(Qt::red);//так работает
    p.setPen(Qt::red);//так работает
    int w=width(),h=height();
    p.drawRect(0,0,w,h);
    p.end();
    QGroupBox::paintEvent(e);
    }

     void MyGroupBox::setColor(QColor c)
    {
    color=c;
    repaint();
    }

    Отсюда вопрос: как правильно изменить цвет QGroupBox?
    Можно ли это сделать, не создавая наследника?
    А если наследник нужен, то как сделать цвет изменяемым?


    Записан
    kambala


    ui.gb->setStyleSheet(«QGroupBox {background-color: red}»);


    Записан

    Изучением C++ вымощена дорога в Qt.

    UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

    _OLEGator_

    Гость


    Типичная ошибка.

    C++ (Qt)

    QWidget::setAutoFillBackground(true);

    Записан
    zzzseregazzz

    Гость


    Уже пробовал

    C++ (Qt)

    ui.gb->setAutoFillBackground(true);

    С ним тоже не работает.
    И

    C++ (Qt)

    ui.gb->setStyleSheet("QGroupBox {background-color: red}");

    тоже не работает

    « Последнее редактирование: Сентябрь 16, 2013, 16:56 от zzzseregazzz »
    Записан
    _OLEGator_

    Гость


    Потому что должно быть так:

    C++ (Qt)

    ui.gb->setStyleSheet("background-color: red");

    Записан
    kambala


    у меня и с и без QGroupBox {} работает (Qt 4.8.5)


    Записан

    Изучением C++ вымощена дорога в Qt.

    UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

    _OLEGator_

    Гость


    to kambala:
    предположил, что возможно с этим проблема — не было возможности проверить.
    у меня setPalette + setAutoFillBackground тоже работает, проверял через Designer.


    Записан
    zzzseregazzz

    Гость


    При этом с QLabel оба метода работают.
    QGroupBox в моей программе помещен в QMainWindow. Если те же операции применить к главному окну (this), то цвет всех элементов успешно меняется (включая QGroupBox).
    Но мне надо поменять только один QGroupBox.

    « Последнее редактирование: Сентябрь 17, 2013, 08:12 от zzzseregazzz »
    Записан
    Bepec

    Гость


    Скиньте свой проект. Полностью. В архиве. С pro файлом.


    Записан
    zzzseregazzz

    Гость


    В общем после пересборки проекта стало работать.
    При этом через setStyleSheet окрашиваются также все кнопки, находящиеся в групбоксе, а через setPalette — только сам групбокс. Так и должно быть?


    Записан
    Bepec

    Гость


    .QGroupBox{background-color: red}

    вроде


    Записан
    kambala


    ui.gb->setStyleSheet(«QGroupBox {background-color: red}»);

    так не должно окрашивать дочерние элементы вообще-то


    Записан

    Изучением C++ вымощена дорога в Qt.

    UTF-8 has been around since 1993 and Unicode 2.0 since 1996; if you have created any 8-bit character content since 1996 in anything other than UTF-8, then I hate you. © Matt Gallagher

    Bepec

    Гость


    Ну именно так я понял его последнее сообщение. Ему нафиг не нужны красные кнопки Улыбающийся

    PS Да, это нормальное поведение. Стайлшит наследуется дочерними элементами. Палитра — не наследуется. Для ограничения наследования стайлшита используется селектор «.» .


    Записан
    zzzseregazzz

    Гость


    Для ограничения наследования стайлшита используется селектор «.»

    Можно пример как его использовать?
    И еще вопрос — как окрасить только внутри рамки? Т.е. обычным способом красится весь прямоугольник с рисунка, хотя в обычной расцветке верхняя граница не видна.

    _____________________
    |—GroupBox—————|
    |                                    |
    |____________________|

    « Последнее редактирование: Сентябрь 18, 2013, 15:54 от zzzseregazzz »
    Записан

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Как изменить цвет footer html
  • Как изменить цвет floating action button
  • Как изменить цвет fieldset
  • Как изменить цвет entry tkinter
  • Как изменить цвет edittext android studio

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии