Important: Please read the Qt Code of Conduct -

Set Dashed Line's Dash And Space Lengths In Pixels Instead Of In Line Width Units

  • As far as I can tell there is no way in Qt to set a dashed line's dash and space lengths in any unit other than multiples of line widths. That is a show stopper for me as I need to set them in pixels in order to draw a dashed line with dashes shorter than the line is wide. Is there any way to do that?

    I did try to set the dash and space lengths as fractions of the line width, but it did not work.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You should explain what you are using to draw these lines and on what you are drawing them.

  • Thanks for the reminder.

    It' just QPainter and QPen in a QPaintEvent on a simple MainWindow. I did this as a test. I have very little Qt experience so I wanted to see if what I want to do is even possible.

  • Lifetime Qt Champion

    Can you show an example of drawing you want to achieve ?

  • WideSpacedLine.png

    Sorry for the delay in getting back.

    The example is a single 130 pixel wide spaced line drawn using the Cairo graphics library, where cr is a cairo context. This works with any Cairo line, not just straight lines.

    I was hoping that Qt had a similar capabilty.

     double dashes[2] = {7.5, 30.0};
     cairo_set_source_rgba(cr, 1.0, 0.0, 0.0, 0.5);     
     cairo_set_line_width(cr, 130);                      
     cairo_set_antialias(cr,  CAIRO_ANTIALIAS_FAST);
     cairo_set_dash(cr, dashes, 2, 5);
     cairo_move_to(cr, 200, 200);
     cairo_line_to(cr, 1000, 200);

  • Lifetime Qt Champion

    Doesn't QPen's width and dash pattern do what you want ?

  • @SGaist

    No, I'm afraid not. From the documentation: The dash pattern is specified in units of the pens width; e.g. a dash of length 5 in width 10 is 50 pixels long.

    And fractional line width units simply don't work. I tried that.

    Frankly I am surprised that the developers did this. I can see line width units for dashes and spaces as a convenience, but not at the expense of not being able to specify them in pixels.

    Unless I can find a way to use a Cairo context in Qt, I am afraid I am not going to be able to use Qt. So far, despite searching, I have found no information on that possibility.

  • Lifetime Qt Champion

    Based on this file from the Cairo sources I would say you should be good to go.

Log in to reply