编辑:Kuba Ober 的建议更加简单和强大,我仍然会在这里留下我的答案,因为我发现它有些有趣(并且可以修改 C++ 自定义组件方法以按照建议过滤窗口事件)。
请原谅我,但我已经写了一个快速而丑陋的 hack,看看它是否可能,它只涵盖了你问题的第二部分(不更新内容)。
我的解决方案会阻止重绘项目,但在请求更新时也会将其隐藏(这对您来说可能不是问题)。
在阅读了QQuickItem::updatePaintNode 文档,尤其是这句话之后
如果用户在项目上设置了 QQuickItem::ItemHasContents 标志,则作为 QQuickItem::update() 的结果调用该函数。
我创建了一个 C++ 类来设置/取消设置任意 QQuickItem 上的这个标志:
#ifndef ITEMUPDATEBLOCKER_H
#define ITEMUPDATEBLOCKER_H
#include <QObject>
#include <QQuickItem>
class ItemUpdateBlocker : public QObject
{
Q_OBJECT
Q_PROPERTY(QQuickItem* target READ target WRITE setTarget NOTIFY targetChanged)
QQuickItem* m_target;
public:
explicit ItemUpdateBlocker(QObject *parent = 0) : QObject(parent), m_target(nullptr) { }
QQuickItem* target() const { return m_target; }
signals:
void targetChanged();
private:
static void blockUpdate(QQuickItem* target)
{
if (target)
target->setFlag(QQuickItem::ItemHasContents, false);
}
static void unblockUpdate(QQuickItem* target)
{
if (target)
{
target->setFlag(QQuickItem::ItemHasContents, true);
target->update();
}
}
public slots:
void setTarget(QQuickItem* target)
{
if (m_target == target)
return;
unblockUpdate(m_target);
blockUpdate(target);
m_target = target;
emit targetChanged();
}
};
#endif // ITEMUPDATEBLOCKER_H
下一步是注册这个类,以便它可以在 QML 中使用:
qmlRegisterType<ItemUpdateBlocker>("com.mycompany.qmlcomponents", 1, 0, "ItemUpdateBlocker");
你可以像这样在 QML 中使用它:
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import com.mycompany.qmlcomponents 1.0
ApplicationWindow {
width: 640
height: 480
visible: true
Rectangle {
color: "red"
id: root
anchors.fill: parent
Text {
text: blocker.target ? "Blocked" : "Not Blocked"
}
Rectangle {
color: "white"
anchors.centerIn: parent
width: parent.width/2
height: parent.height/2
ItemUpdateBlocker {
id: blocker;
}
MouseArea {
anchors.fill: parent
onClicked: blocker.target = blocker.target ? null : parent
}
}
}
}
您当然可以将active 属性添加到阻止程序以简化其使用(比使用空target 禁用它更漂亮),但我将把它留作练习。
也许您可以在 Window 的宽度或高度发生更改时启动计时器,但我还没有找到直接的方法来确定窗口是否已调整大小。