Qt QGridLayout bug

如果需要让一个窗口支持模态和非模态窗口,一般是需要将改窗口设置为QDailog,

实现该功能的一个关键点是设置了setStyleSheet(Qt::Window),源码如下:

        Widget = 0x00000000,

        Window = 0x00000001,

        Dialog = 0x00000002 | Window,

 

Qt::Dialog

0x00000002 | Window

Indicates that the widget is a window that should be decorated as a dialog (i.e., typically no maximize or minimize buttons in the title bar). This is the default type for QDialog. If you want to use it as a modal dialog, it should be launched from another window, or have a parent and used with the QWidget::windowModality property. If you make it modal, the dialog will prevent other top-level windows in the application from getting any input. We refer to a top-level window that has a parent as a secondary window.

 

 

确实可以使用QDialog实现模态和非模态对话框的功能,还有其他方法实现类似的功能吗,可以使用QWidget实现类似的效果吗,可以使用QWidget实现窗口置顶且为非模态对话框的功能,如果需求不要求是模态对话框,只需要窗口置顶和非模态窗口,可以使用QDialog实现类似的功能,也可以使用QWidget实现,QWidget本身默认是没有这样的功能的需要多做一些设置就可以实现了,可以设置QWidget::setWindowsFlags(this->windowsFlags() | Qt::Window),就可以有这样的功能。

设置了Qt::Window标志之后,窗口就具有一直置顶的功能,且为非模态对话框的功能。所以如果需求是这样的话,既可以使用QDialog实现,也可以使用QWindow实现,设置Qt::Window就可以了,不需要再设置窗口一直置顶等类似的windowFlags也可以实现非模态对话框且窗口置顶的功能。当然如果需求要求是模态对话框,建议还是用现成封装好的QDialog就可以了。

如果需要实现模态对话框功能,但是窗口效果确实非模态的,可以使用QWidget,QWidget::setWindowsFlags(this->windowsFlags() | Qt::Window),就可以实现模态对话框的窗口效果,再加上使用

     show();
     QEventLoop evtLoop;
     m_pEvtLoop = &evtLoop;
     evtLoop.exec();

然后再弹出的非模态窗口的自定义确定取消按钮做如下操作就可以了

void ColorDialog::okBtnClickedSlot()

{

    m_buttonRole = Yes;

    if (m_pEvtLoop != NULL)

    {

        m_pEvtLoop->exit();

    }

    this->hide();

}

 

void ColorDialog::cancelBtnClickedSlot()

{

    m_buttonRole = No;

    if (m_pEvtLoop != NULL)

    {

        m_pEvtLoop->exit();

    }

    this->hide();

}

 

 

Qt QGridLayout相关的bug

在使用Qt的网格布局的时候,可以将各种数据比如QWidget表格顺序整齐的排列好,但是在具体使用中,发现QGridLayout并没有达到预期的对齐和显示效果,应该是Qt底层内核相关的一个bug,具体如下,如果用QGridLayout,做出一个颜色样板

仔细看会发现有些间隔显得有点宽,有些间隔显得有点窄,具体代码如下

    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    this->setContentsMargins(0, 0, 0, 0);

    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint);

    this->setAttribute(Qt::WA_TranslucentBackground);

    this->setStyleSheet("border:0px;");

void BasicColorItem::paintEvent(QPaintEvent *ev)

{

    QPainter painter(this);

    painter.setRenderHint(QPainter::Antialiasing);

    painter.setPen(Qt::NoPen);

    painter.setBrush(m_color);

    painter.drawRect(0, 0, width(), height());

}

该做的设置应该多是做了的,还是做不到间隔均衡显示,如不把item背景颜色换为相同就可以了,这可能应该和qt相关的内核或者这方面的底层渲染没有弄好,所以说这个应该可以说是qt的一个bug,所以如果不在意这么一点瑕疵可以就使用这种方式就可以了,如果需要解决这样的bug,可以考虑使用QTableWidget等类似的组件代替使用QGridLayout。

发布了85 篇原创文章 · 获赞 18 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/a1317338022/article/details/105556292