c++ - 为什么 setwidth 为其他值 1 会使我的线消失?

标签 c++ qt

正如我的代码片段中的评论所解释的:

对于笔设置为 noneSelectedLine 且笔宽度为 != 1 的行,代码无法按预期工作。

scene = new QGraphicsScene();
Qt::PenStyle ePenStyl = Qt::DashLine;
selectedLine = new QPen(Qt::blue);
noneSelectedLine =  new QPen(Qt::red);
selectedLine->setWidth(2);
noneSelectedLine->setWidth(1); 
noneSelectedLine->setDashPattern(QVector<qreal>(ePenStyl));

/*If this line is a comment all is running as expected, but as soon as I 
set in the following line, all lines where the pen is set to 
noneSelectedLine they are not drawn (or at least not visible). What could 
be the reason for that?*/

//noneSelectedLine->setWidth(3); 

for (int indexI = 0; indexI < 5; indexI++)
{
    scene->addItem(&LineSet[indexI]);
}

这是什么原因呢? 如果代码片段中缺少某些信息,请告诉我,我会进行澄清。

最佳答案

您的代码存在多个问题。首先, vector 构造函数的这个重载QVector<qreal>(something)创建 qreal 的 vector 大小为something元素,每个元素都将使用默认值进行初始化。

第二,Qt::DashLineenum解析为 2 的值,所以行 QVector<qreal>(ePenStyl)创建一个 vector 2 qreal s,其值为 0。

第三,setDashPattern并不像你想象的那样工作。这是一个报价from the doc :

Sets the dash pattern for this pen to the given pattern. This implicitly converts the style of the pen to Qt::CustomDashLine.

The pattern must be specified as an even number of positive entries where the entries 1, 3, 5... are the dashes and 2, 4, 6... are the spaces.

我想你想做的是

noneSelectedLine->setStyle( ePenStyl );

而不是

noneSelectedLine->setDashPattern(QVector<qreal>(ePenStyl));

关于c++ - 为什么 setwidth 为其他值 1 会使我的线消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605885/

相关文章:

c++ - 在 SDL 1.2 中移动 SDL 窗口

c++ - 尝试在构造函数中设置成员变量时代码中断

c++ - 在 ViennaCL 中从 std::vector 转换为 ublas::compressed_matrix

c++ - 围绕 C Dirent.h 的现代 C++ 包装器

C++ 自动与自动&

c++ - MacOS 上Qt GUI Widget 大小异常

qt - 有没有办法在 Qt5 qml 中执行 C++ 宏?

C++ 静态类的静态成员永远不会被引用。它肯定会被初始化还是可以从二进制文件中省略?

c++ - 在 windows 中使用互斥量进行进程间同步(win32 或 C++)

c++ - 设置16位灰度QImage的像素值