python - PyQt5动态添加矩形到QML网格

标签 python qt pyqt qml pyqt5

我在 QML 中构建了一个矩形网格,该网格从 Python 运行。 engine.load('main.qml')

Window {
    id: channels
    Grid {
        columns: 2
        spacing: 9
        Rectangle {
            color: "#333"
            width: 75
            height: 75
        }
        Rectangle {
            color: "#333"
            width: 75
            height: 75
        }
    }
}

但是,我想要超过 50 个矩形,因此我需要能够从 python 动态创建和更新它们。我怎样才能做到这一点?

最佳答案

要从 python(或 C++)向 qml 提供信息,我们可以阅读此 link 。其中建议使用QAbstractListModel因为这会通知 qml 的更改,所以除了动态添加之外,我们还将使用 Repeater .

ma​​in.qml:

import QtQuick.Window 2.2
import QtQuick 2.0
import QtQuick.Controls 1.4

Window {
    visible: true
    id: channels

    Grid {
        columns: 3
        spacing: 9
        Repeater{
            model: myModel
            delegate: Rectangle{
                height: model.height
                width: model.height
                color: model.color
            }
        }
    }
}

.py:

class Data(object):
    def __init__(self, width=35, height=35, color=QColor("red")):
        self._width = width
        self._height = height
        self._color = color

    def width(self):
        return self._width

    def height(self):
        return self._height

    def color(self):
        return self._color

class Model(QAbstractListModel):

    WidthRole = Qt.UserRole + 1
    HeightRole = Qt.UserRole + 2
    ColorRole = Qt.UserRole + 3

    _roles = {WidthRole: b"width", HeightRole: b"height", ColorRole: b"color"}

    def __init__(self, parent=None):
        QAbstractListModel.__init__(self, parent)

        self._datas = []

    def addData(self, data):
        self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount())
        self._datas.append(data)
        self.endInsertRows()

    def rowCount(self, parent=QModelIndex()):
        return len(self._datas)

    def data(self, index, role=Qt.DisplayRole):
        try:
            data = self._datas[index.row()]
        except IndexError:
            return QVariant()

        if role == self.WidthRole:
            return data.width()

        if role == self.HeightRole:
            return data.height()

        if role == self.ColorRole:
            return data.color()

        return QVariant()

    def roleNames(self):
        return self._roles

为了进行测试,我们使用以下代码:

ma​​in.py

if __name__ == "__main__":
    import sys
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    model = Model()
    model.addData(Data(44, 33, QColor("red")))
    model.addData(Data(23, 53, QColor("#333")))

    context = engine.rootContext()
    context.setContextProperty('myModel', model)

    engine.load(QUrl.fromLocalFile("main.qml"))

    if len(engine.rootObjects()) == 0:
        sys.exit(-1)

    qsrand(QTime.currentTime().msec())
    timer = QTimer(engine)
    timer.timeout.connect(lambda: model.addData(Data(20 + qrand() % 40, 
                                                     20 + qrand() % 40, 
                                                     QColor(qrand() % 255, qrand() % 255, qrand() % 255))))
    timer.start(1000)

    engine.quit.connect(app.quit)

    sys.exit(app.exec_())

您找到的完整示例here .

关于python - PyQt5动态添加矩形到QML网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373279/

相关文章:

python - 是否有任何 ipdb 打印寻呼机?

python - 试图欺骗电子邮件地址

c++ - 如何在 QLatin1String 中搜索子字符串?

python - 如何在 PyQt5 中获取当前聚焦的小部件对象名称?

python - docker容器内的多个线程

python - 查看一个素筛程序,但不确定为什么它不断出现有关切片长度的错误

c++ - QT中指针 vector 的访问 vector

c++ - QInputDialog 和 QMessageBox

python - PyQt Drop Event 没有子类化?

python - 如何使用 PyQt 使用 python 打印包含特殊字符的 QString?