CardViewNewCardFeature Example

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../../shared")

from DevMachines import __pyside2__, __pyside6__
from DevMachines import QtitanBase
from DevMachines.QtitanBase import Qtitan
from DevMachines.QtitanGrid import (getGridVersion, CardGrid, GridColumn, GridEditor,
                                    CellButtonClickEventArgs, CellButtonEventArgs, ContextMenuEventArgs,
                                    EditorValidationEventArgs, EditorLinkEventArgs)

if __pyside2__:
    from PySide2 import QtCore
    from PySide2.QtCore import Qt, QStringListModel
    from PySide2.QtGui import QPixmap, QStandardItemModel
    from PySide2.QtWidgets import (QWidget, QApplication, QVBoxLayout, QHBoxLayout, QPushButton,
                                   QSlider, QLabel, QCheckBox, QComboBox, QMessageBox, QFileDialog)
    from PySide2.QtSql import QSqlDatabase, QSqlError, QSqlTableModel

if __pyside6__:
    from PySide6 import QtCore
    from PySide6.QtCore import Qt, QStringListModel
    from PySide6.QtGui import QPixmap, QStandardItemModel
    from PySide6.QtWidgets import (QWidget, QApplication, QVBoxLayout, QHBoxLayout, QPushButton,
                                   QSlider, QLabel, QCheckBox, QComboBox, QMessageBox, QFileDialog)
    from PySide6.QtSql import QSqlDatabase, QSqlError, QSqlTableModel

from DemoMainWindow import DemoMainWindow

import CardViewNewCardFeature_rc

def add_model_item(model, photo, name, titleIndex, countryIndex, city, code, geoLocation):
    row = model.rowCount()
    model.insertRow(row)

    model.setData(model.index(row, 0), photo)
    model.setData(model.index(row, 1), name)
    model.setData(model.index(row, 2), titleIndex)
    model.setData(model.index(row, 3), countryIndex)
    model.setData(model.index(row, 4), city)
    model.setData(model.index(row, 5), code)
    link = "<a href='http://www.geonames.org/maps/google_" + geoLocation + ".html'>" + geoLocation + "</a>"
    model.setData(model.index(row, 6), link)

    previewText = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sodales,
                     libero at hendrerit commodo, urna velit vestibulum purus, cursus dignissim tellus ante non leo.
                     Donec sed neque sit amet mauris iaculis varius ac eu ipsum. <b>Proin vel hendrerit magna</b>.
                     Curabitur posuere ligula eu turpis porttitor faucibus rhoncus neque pretium. Duis quam lorem, bibendum id luctus eu, consequat at purus.
                     Aenean ut urna felis."""
    # model.setData(model.index(0, 0), previewText, Qt.WhatsThisRole)

def create_model(parent):
    model = QStandardItemModel(0, 7, parent)

    model.setHeaderData(0, Qt.Horizontal, model.tr("Photo"))
    model.setHeaderData(1, Qt.Horizontal, model.tr("Name"))
    model.setHeaderData(2, Qt.Horizontal, model.tr("Title"))
    model.setHeaderData(3, Qt.Horizontal, model.tr("Country"))
    model.setHeaderData(4, Qt.Horizontal, model.tr("City"))
    model.setHeaderData(5, Qt.Horizontal, model.tr("Postal Code"))
    model.setHeaderData(6, Qt.Horizontal, model.tr("Location"))

    add_model_item(model, QPixmap(":res/photo2.png"), "Dietrich Wolf"
        , 0 # Founder
        , 0 # Germany
        , "Berlin", "10245", "52.517_13.4")
    add_model_item(model, QPixmap(":res/photo1.png"), "Albert Schneider"
        , 1 # President
        , 0 # Germany
        , "Berlin", "10178", "52.523_13.414")
    add_model_item(model, QPixmap(":res/photo3.png"), "Adelina Adams"
        , 3 # Sales Manager
        , 0 # Germany
        , "Berlin", "10707", "52.517_13.4")
    add_model_item(model, QPixmap(":res/photo4.png"), "Bertrand Maison"
        , 4 # Software Engineer
        , 1 # France
        , "Paris", "75003", "48.864_2.361")
    add_model_item(model, QPixmap(":res/photo5.png"), "Anna Laroche"
        , 3 # Sales Manager
        , 1 # France
        , "Saint-Bernard", "68720", "47.667_7.2")
    add_model_item(model, QPixmap(":res/photo6.png"), "Dominik Malet"
        , 4 # Software Engineer
        , 1 # France
        , "Pulversheim", "68840", "47.838_7.301")
    add_model_item(model, QPixmap(":res/photo7.png"), "Berta Padovano"
        , 2 # Vice President
        , 2 # Italy
        , "Milano", "20121", "45.464_9.19")
    add_model_item(model, QPixmap(":res/photo8.png"), "Andrew Armstrong"
        , 5 # Software Developer
        , 2 # Italy
        , "Modena", "41100", "44.648_10.925")
    add_model_item(model, QPixmap(":res/photo9.png"), "Caterina Venezia"
        , 6 # Head of Sales
        , 2 # Italy
        , "Roma", "00136", "41.892_12.511")
    add_model_item(model, QPixmap(":res/photo10.png"), "Sophia Smith"
        , 7 # Technical Support
        , 3 # United States
        , "Boston", "02115", "42.343_-71.092")
    add_model_item(model, QPixmap(":res/photo11.png"), "Jacob Morris"
        , 3 # Software Engineer
        , 3 # United States
        , "York", "10001", "40.748_-73.997")
    add_model_item(model, QPixmap(":res/photo12.png"), "Andrew Fisher"
        , 5 # Software Developer
        , 3 # United States
        , "Miami Beach", "33140", "25.82_-80.134")
    add_model_item(model, QPixmap(":res/photo13.png"), "Isabella Henderson"
        , 7 # Technical Support
        , 4 # United Kingdom
        , "Manchester", "M60", "53.481_-2.237")
    add_model_item(model, QPixmap(":res/photo14.png"), "Olivia Hewitt"
        , 7 # Technical Support
        , 4 # United Kingdom
        , "Richmond", "TW9", "51.46_-0.301")
    add_model_item(model, QPixmap(":res/photo15.png"), "Daniel Fuller"
        , 8 # Administration Manager
        , 4 # United Kingdom
        , "Notting Hill", "W11", "51.511_-0.206")
    return model

class Window(DemoMainWindow):
    def __init__(self):
        DemoMainWindow.__init__(self, "QtitanDataGrid", getGridVersion())

        self.setWindowTitle(self.tr("QtitanDataGrid - CardView add row demo"))
        self.setGeometry(150, 150, 1000, 800)

        CardGrid.loadTranslation()

        self.grid = CardGrid()
        model = create_model(self.grid)

        # Configure grid view
        self.grid.setViewType(CardGrid.CardView)
        view = self.grid.view()
        view.options().setNewRowPlace(Qtitan.AtBeginning)

        # Connect Grid's context menu handler.
        self.connect(view, QtCore.SIGNAL("contextMenu(ContextMenuEventArgs*)"), self,
            QtCore.SLOT("contextMenu(ContextMenuEventArgs* )"))
        self.connect(view, QtCore.SIGNAL("editorLinkActivated(EditorLinkEventArgs*)"), self,
            QtCore.SLOT("editorLinkActivated(EditorLinkEventArgs*)"))

        view.setModel(model)

        column = view.getColumnByModelColumnName("Photo")
        column.setEditorType(GridEditor.Picture)
        column.setRowSpan(4)
        #QVariant defValue = GridPictureEditorRepository.convertToVariant(
        #    QVariant.ByteArray, QPixmap(":res/new_user.png"))
        #column.editorRepository().setDefaultValue(defValue, Qt.DisplayRole)
        #column.editorRepository().setDefaultValue(defValue, Qt.EditRole)

        column = view.getColumnByModelColumnName("Title")
        column.setEditorType(GridEditor.ComboBox)
        titleModel = QStringListModel(column)
        options = ["Founder", "President", "Vice President", "Sales Manager",
                   "Software Engineer", "Software Developer",
                   "Head of Sales", "Technical Support", "Administration Manager"]
        titleModel.setStringList(options)
        column.dataBinding().setRelationModel(titleModel)

        column = view.getColumnByModelColumnName("Country")
        column.setEditorType(GridEditor.ComboBox)
        countryModel = QStringListModel(column)
        options.clear()
        options = ["Germany", "France", "Italy", "United States",
                   "United Kingdom", "Russia", "China", "Canada"]
        countryModel.setStringList(options)
        column.dataBinding().setRelationModel(countryModel)

        column = view.getColumnByModelColumnName("Location")
        column.setEditorType(GridEditor.Memo)
        column.editorRepository().setHTML(True)

        # Show button menu for all column headers.
        for i in range(0, view.getColumnCount()):
            view.getColumn(i).setMenuButtonVisible(True)

        self.setDemoWidget(self.grid, self.createSettingsWidget())

        view.bestFit()

        # self.addPreviewRow()

    def createSettingsWidget(self):
        # Create settings widget
        settings = QWidget(self)
        l = QVBoxLayout(settings)

        placeLabel = QLabel(settings)
        placeLabel.setText(self.tr("Card pane place:"))
        newRowPosition = QComboBox(settings)
        newRowPosition.addItem("Top")
        newRowPosition.addItem("Bottom")
        newRowPosition.addItem("Hide")
        self.connect(newRowPosition, QtCore.SIGNAL("currentIndexChanged(int)"), self,
            QtCore.SLOT("newRowPositionActivated(int)"))
        placeLabel.setBuddy(newRowPosition)
        hl = QHBoxLayout()
        hl.addWidget(placeLabel)
        hl.addWidget(newRowPosition)
        l.addLayout(hl)

        effectLabel = QLabel(settings)
        effectLabel.setText(self.tr("Highlight effect:"))
        newRowEffect = QComboBox(settings)
        newRowEffect.addItem("Flash")
        newRowEffect.addItem("Alpha")
        self.connect(newRowEffect, QtCore.SIGNAL("currentIndexChanged(int)"), self,
            QtCore.SLOT("newRowEffectActivated(int)"))
        effectLabel.setBuddy(newRowEffect)
        hl = QHBoxLayout()
        hl.addWidget(effectLabel)
        hl.addWidget(newRowEffect)
        l.addLayout(hl)

        fastScrollCheck = QCheckBox(settings)
        fastScrollCheck.setText("Fast scroll effect")
        self.connect(fastScrollCheck, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("fastScrollChanged(int)"))
        l.addWidget(fastScrollCheck)
        fastScrollCheck.setChecked(True)

        dottedLineCheck = QCheckBox(settings)
        dottedLineCheck.setText("Dotted grid line")
        self.connect(dottedLineCheck, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("dottedLineChanged(int)"))
        l.addWidget(dottedLineCheck)
        dottedLineCheck.setChecked(False)

        label = QLabel(self)
        hl = QHBoxLayout()
        label.setText("Grid line style:")
        lineStylesSelect = QComboBox(settings)

        lineStylesSelect.addItem("None")
        lineStylesSelect.addItem("Both")
        lineStylesSelect.addItem("Both2D")
        lineStylesSelect.addItem("Horizontal")
        lineStylesSelect.addItem("Horizontal2D")
        lineStylesSelect.addItem("Vertical")
        lineStylesSelect.addItem("Vertical2D")
        self.connect(lineStylesSelect, QtCore.SIGNAL("currentIndexChanged(int)"), self,
            QtCore.SLOT("selectGridLineStyles(int)"))
        hl.addWidget(label)
        hl.addWidget(lineStylesSelect)
        l.addLayout(hl)
        lineStylesSelect.setCurrentIndex(3)

        zoomEnable = QCheckBox(settings)
        zoomEnable.setText(self.tr("Zoom enabled"))
        zoomEnable.setChecked(True)
        self.connect(zoomEnable, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("zoomEnabledChanged(int)"))
        l.addWidget(zoomEnable)

        zoomIndicator = QCheckBox(settings)
        zoomIndicator.setText(self.tr("Show zoom indicator"))
        zoomIndicator.setChecked(True)
        self.connect(zoomIndicator, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("zoomIndicatorChanged(int)"))
        l.addWidget(zoomIndicator)

        zoomSlider = QSlider(settings)
        zoomSlider.setOrientation(Qt.Horizontal)
        zoomSlider.setTickPosition(QSlider.TicksBothSides)
        zoomSlider.setMinimum(25)
        zoomSlider.setMaximum(300)
        zoomSlider.setTickInterval(25)
        zoomSlider.setSingleStep(25)
        zoomSlider.setValue(100)
        self.connect(zoomSlider, QtCore.SIGNAL("sliderMoved(int)"), self, QtCore.SLOT("zoomValueChanged(int)"))
        self.connect(self.grid.view(), QtCore.SIGNAL("zoomChanged(int)"), zoomSlider, QtCore.SLOT("setValue(int)"))
        l.addWidget(zoomSlider)

        cellAutoRaise = QCheckBox(settings)
        cellAutoRaise.setText(self.tr("Auto raise cell button"))
        self.connect(cellAutoRaise, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("cellButtonAutoRaiseEnabled(int)"))
        cellAutoRaise.setChecked(True)
        l.addWidget(cellAutoRaise)
    #
    #   QCheckBox* previewExpandButtonBox = QCheckBox(settings)
    #   previewExpandButtonBox.setText(self.tr("Preview Expand Button (new)"))
    #   self.connect(previewExpandButtonBox, QtCore.SIGNAL("stateChanged(int)"), self, QtCore.SLOT(previewExpandButtonEnabled(int)))
    #   previewExpandButtonBox.setChecked(True)
    #   l.addWidget(previewExpandButtonBox)
    #
        transparentBox = QCheckBox(settings)
        transparentBox.setText(self.tr("Transparent Background"))
        self.connect(transparentBox, QtCore.SIGNAL("stateChanged(int)"), self,
            QtCore.SLOT("transparentBackgroundEnabled(int)"))
        transparentBox.setChecked(False)
        l.addWidget(transparentBox)

        printButton = QPushButton(settings)
        printButton.setText(self.tr("Print Preview"))
        self.connect(printButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("printPreview()"))
        l.addWidget(printButton)
        return settings

    @QtCore.Slot(int)
    def newRowPositionActivated(self, index):
        view = self.grid.view()

        if index == 0:
            view.options().setNewRowPlace(Qtitan.AtBeginning)
        elif index == 1:
            view.options().setNewRowPlace(Qtitan.AtEnd)
        else:
            view.options().setNewRowPlace(Qtitan.AtNone)

    @QtCore.Slot(int)
    def newRowEffectActivated(self, index):
        view = self.grid.view()
        if index == 0:
            view.options().setNewRowHighlightEffect(Qtitan.FlashEffect)
        elif index == 1:
            view.options().setNewRowHighlightEffect(Qtitan.AlphaEffect)
        else:
            view.options().setNewRowHighlightEffect(Qtitan.AlphaEffect)

    @QtCore.Slot(int)
    def fastScrollChanged(self, state):
        view = self.grid.view()
        view.options().setFastScrollEffect(Qt.CheckState(state) == Qt.Checked)

    @QtCore.Slot(int)
    def dottedLineChanged(self, state):
        view = self.grid.view()
        pen = view.options().gridLinePen()
        if Qt.CheckState(state) == Qt.Checked:
            pen.setStyle(Qt.DotLine)
        else:
            pen.setStyle(Qt.SolidLine)
        view.options().setGridLinePen(pen)

    @QtCore.Slot(int)
    def selectGridLineStyles(self, index):
        view = self.grid.view()
        if index == 0:
            view.options().setGridLines(Qtitan.LinesNone)
        elif index == 1:
            view.options().setGridLines(Qtitan.LinesBoth)
        elif index == 2:
            view.options().setGridLines(Qtitan.LinesBoth2D)
        elif index == 3:
            view.options().setGridLines(Qtitan.LinesHorizontal)
        elif index == 4:
            view.options().setGridLines(Qtitan.LinesHorizontal2D)
        elif index == 5:
            view.options().setGridLines(Qtitan.LinesVertical)
        elif index == 6:
            view.options().setGridLines(Qtitan.LinesVertical2D)
        else:
            view.options().setGridLines(Qtitan.LinesBoth)

    @QtCore.Slot(int)
    def zoomEnabledChanged(self, state):
        view = self.grid.view()
        view.options().setZoomEnabled(Qt.CheckState(state) == Qt.Checked)

    @QtCore.Slot(int)
    def zoomIndicatorChanged(self, state):
        view = self.grid.view()
        view.options().setZoomIndicatorActive(Qt.CheckState(state) == Qt.Checked)

    @QtCore.Slot(int)
    def zoomValueChanged(self, value):
        factor = (float(value) / 25) * 25
        view = self.grid.view()
        view.options().setZoomFactor(factor / 100)

    @QtCore.Slot(int)
    def cellButtonAutoRaiseEnabled(self, state):
        view = self.grid.view()
        view.options().setCellButtonAutoRaise(Qt.CheckState(state) == Qt.Checked)

    @QtCore.Slot(int)
    def transparentBackgroundEnabled(self, state):
        view = self.grid.view()
        view.options().setTransparentBackground(Qt.CheckState(state) == Qt.Checked)
        view.options().setAlternatingRowColors(not view.options().alternatingRowColors())

    @QtCore.Slot(int)
    def previewExpandButtonEnabled(self, state):
        view = self.grid.view()
        view.options().setPreviewExpandButtonVisible(Qt.CheckState(state) == Qt.Checked)

    @QtCore.Slot(ContextMenuEventArgs)
    def contextMenu(self, args):
        args.contextMenu().addAction("Print Preview", self, QtCore.SLOT("printPreview()"))
        args.contextMenu().addSeparator()
        args.contextMenu().addAction("Developer Machines on the Web", self, QtCore.SLOT("showCompanyWebSite()"))

    @QtCore.Slot(EditorLinkEventArgs)
    def editorLinkActivated(self, args):
        view = self.grid.view()
        if not view.isEditing():
            QDesktopServices.openUrl(QUrl(args.anchor()))

    @QtCore.Slot(CellButtonClickEventArgs)
    def cellButtonClicked(self, args):
        QMessageBox.information(self, "Cell button clicked",
            "Clicked: Button - " + str(args.buttonIndex()) + ", Column Title - " + args.column().caption() + ", RowIndex - " + str(args.row().rowIndex()))

    @QtCore.Slot()
    def printPreview(self):
        self.grid.view().printPreview()

    def setShadeColor(self, color):
        self.grid.themeManager().setShadeColor(color)

    def addPreviewRow(self):
        view = self.grid.view()
        view.options().setPreviewRowEnabled(True)
        view.modelController().previewRowDataBinding().setDisplayRole(Qt.WhatsThisRole)
        view.options().setPreviewRowHeight(100)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Window()
    w.show()
    sys.exit(app.exec_())