简体   繁体   English

Qt - 每次调用 show() function 时,如何将信号连接到 QGroupBox?

[英]Qt - How can I connect a signal to a QGroupBox each time the show() function is called on it?

I have two classes that are interacting with each other, let's call them for the sake of simplicity ClassA and ClassB .我有两个相互交互的类,为了简单起见,我们称它们为ClassAClassB In ClassA , I would like to emit a signal when a specific QGroupBox is shown that triggers a slot in ClassB to set the given channel's checkbox.ClassA中,我想在显示特定QGroupBox时发出一个信号,该信号触发ClassB中的插槽以设置给定通道的复选框。

I have a code that consists of several thousand lines, so I included only the most relevant parts.我有一个包含几千行的代码,所以我只包含了最相关的部分。

ClassA header A类 header

private:
QGroupbox* m_Channel1GroupBox;
void setup();

signals:
void setCheckBox(int, bool);

ClassA source A 类源

void ClassA::setup()
{
    m_Channel1GroupBox = new QGroupBox("Channel 1", this);

    connect(m_Channel1GroupBox, &QGroupBox::show, [this]()
    {
        emit setCheckBox(1, true);
    });
}

ClassB header B类 header

private:
QCheckBox* m_Channel1CheckBox;

public slots:
void setCheckBox(int, bool);

ClassB source B 类源

void ClassB::setCheckBox(int channel, bool check)
{
    if (channel == 1)
    {
        m_Channel1CheckBox->setChecked(check);
    }
}

Main.cpp主文件

connect(m_ClassA, &ClassA::setCheckBox, m_ClassB, &ClassB::setCheckBox);

The lambda expression compiles, but unfortunately it doesn't do what it is expected to do, which is whenever m_Channel1GroupBox->show() is called, then tick the checkbox of Channel1. lambda 表达式可以编译,但不幸的是它并没有按照预期执行,即每当调用 m_Channel1GroupBox->show() 时,然后勾选 Channel1 的复选框。 Actually this block of code never executes, which would emit setCheckBox .实际上,这段代码永远不会执行,它会发出setCheckBox

Please note that the setCheckBox function works perfectly when called in another function of ClassA and it checks or unchecks the desired channel in ClassB .请注意,当在ClassA的另一个 function 中调用setCheckBox function 时,它可以完美地工作,并且它会检查或取消选中ClassB中所需的通道。 This is possible using another connect in the Main.cpp file where the object instances are created.这可以在创建 object 实例的 Main.cpp 文件中使用另一个连接来实现。

run the code and you will see that the运行代码,你会看到

QGroupBox has no signal to emit called show ... show is actually a slot QGroupBox没有发出信号,称为show ... show 实际上是一个插槽

在此处输入图像描述

QObject::connect: signal not found in QGroupBox QObject::connect: 在 QGroupBox 中找不到信号

But... if you are calling show per hand, then emit the signal right after that...但是...如果您是手动调用 show ,则在此之后立即发出信号...

You will need to subclass QGroupBox to achieve the functionality you require.您将需要继承 QGroupBox 以实现您需要的功能。

Override QWidget::showEvent(QShowEvent*) in your QGroupBox subclass and do the work there.在您的 QGroupBox 子类中覆盖 QWidget::showEvent(QShowEvent*) 并在那里完成工作。

Please see the documentation for QWidget .请参阅QWidget 的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM