编辑:Kuba Ober建议的方法更加简单和稳健,我仍然保留我的答案,因为我认为它有些有趣(可以修改C++自定义组件方法来过滤窗口事件,如建议所述)。
抱歉,我写了一个快速且不太美观的黑客来测试是否可能,它仅涵盖了您问题的第二部分(不更新内容)。我的解决方案阻止了Item的重绘,但是也在请求更新时立即隐藏了它(这对您可能不是问题)。
阅读
QQuickItem :: updatePaintNode文档,特别是这句话后,我创建了一个C++类来设置/取消设置此标志在任意QQuickItem上:
“如果用户在项目上设置了QQuickItem :: ItemHasContents标志,则将调用该函数作为QQuickItem :: update()的结果。”
#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
下一步是注册这个类,以便在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”禁用它更美观),但我会把这留作练习。
也许你可以在窗口的宽度或高度改变时启动一个定时器,我还没有找到直接找到窗口是否被调整大小的方法。
QGuiApplication::mouseButtons
返回没有任何按钮被按下。 - GrecKo