void AddressBookPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which address was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);

    Q_FOREACH (const QModelIndex& index, indexes) {
        QVariant address = table->model()->data(index);
        returnValue = address.toString();
    }
void AcceptedOfferListPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which offer was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(OfferAcceptTableModel::Name);

    Q_FOREACH (const QModelIndex& index, indexes)
    {
        QVariant offer = table->model()->data(index);
        returnValue = offer.toString();
    }
Esempio n. 3
0
void MyCertListPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which cert was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(CertTableModel::Name);

    Q_FOREACH (const QModelIndex& index, indexes)
    {
        QVariant cert = table->model()->data(index);
        returnValue = cert.toString();
    }
Esempio n. 4
0
void MainWindow::createSongsTable(int size)
{
    QTableView * songs = ui->tvSongs;

    delete songs->model();
    delete songs->selectionModel();
    QStandardItemModel *model = new QStandardItemModel(size, 3, songs);
    QItemSelectionModel *selections = new QItemSelectionModel(model);

    songs->setModel(model);
    songs->setSelectionModel(selections);

    songs->horizontalHeader()->setSectionsMovable(true);
    songs->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    songs->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);

    songs->verticalHeader()->setSectionsMovable(false);
    songs->verticalHeader()->setVisible(false);

    songs->setSelectionBehavior( QAbstractItemView::SelectRows );
    songs->setSelectionMode( QAbstractItemView::SingleSelection );

    songs->setContextMenuPolicy(Qt::CustomContextMenu);

    // Set StaticContents to enable minimal repaints on resizes.
    songs->viewport()->setAttribute(Qt::WA_StaticContents);

    model->setHorizontalHeaderItem(0, new QStandardItem(tr("Artist")));
    model->setHorizontalHeaderItem(1, new QStandardItem(tr("Title")));
    model->setHorizontalHeaderItem(2, new QStandardItem(tr("Length")));
}
Esempio n. 5
0
void MainWindow::accountItemActivated(const QModelIndex & index)
{
    if (index.model() != m_accountTreeModel
            && index.model() != m_accountListModel)
    {
        qDebug() << "Wrong model; row=" << (index.isValid()? index.row() : -1);
        return;
    }
    Glib::RefPtr<Account> account = Glib::wrap(static_cast< ::Account*>(index.internalPointer()));
    if (!account)
    {
        qDebug() << "Account is null; why?";
        return;
    }

    // We create a new model for this account which will query it for
    // its splits, and also a view widget for this list.
    QTableView *tableView =
        new SplitListView(account, m_undoStack, ui->tabWidget);
    ui->actionCut->setEnabled(tableView->model()->rowCount() > 0);

    // Insert this as a new tab
    tableView->setProperty(PROPERTY_TAB_PREVIOUSPOS, ui->tabWidget->currentIndex());
    ui->tabWidget->addTab(tableView, g2q(account->get_name()));
    ui->tabWidget->setCurrentWidget(tableView);

    connect(tableView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
            this, SLOT(selectionChanged(const QItemSelection &, const QItemSelection & )));
}
Esempio n. 6
0
void ReceiptPage::selectionChanged()
{
    // Set button states based on selected tab and selection
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;

    if(table->selectionModel()->hasSelection())
    {
        replyAction->setEnabled(true);
        copyFromAddressAction->setEnabled(true);
        copyToAddressAction->setEnabled(true);
        deleteAction->setEnabled(true);

        ui->copyFromAddressButton->setEnabled(true);
        ui->copyToAddressButton->setEnabled(true);
        ui->replyButton->setEnabled(true);
        ui->deleteButton->setEnabled(true);

        // Figure out which message was selected, and return it
        QModelIndexList typeColumn = table->selectionModel()->selectedRows(InvoiceTableModel::Type);

        foreach (QModelIndex index, typeColumn)
        {
            bool sent = (table->model()->data(index).toString() == MessageModel::Sent);

            resendAction->setEnabled(sent);
            ui->resendButton->setEnabled(sent);
            ui->resendButton->setVisible(sent);
        }
Esempio n. 7
0
bool DataViewer::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::RightButton)
        {
            const QPoint globalMousePos = mouseEvent->globalPos();

            QTableView *tableView = d_ptr->m_tableData;
            Q_ASSERT(tableView);

            const QModelIndex tableModelIndex = tableView->indexAt(mouseEvent->pos());
            if (tableModelIndex.isValid())
            {
                QVariant data = tableView->model()->data(tableModelIndex);
                bool ok = false;
                int timestamp = data.toInt(&ok);
                if (ok)
                {
                    QMenu menu;
                    menu.addAction(d_ptr->m_timestampAction);
                    if (menu.exec(globalMousePos))
                    {
                        QMessageBox::information(this, QString(), QDateTime::fromTime_t(timestamp).toString());
                    }
                }
            }
        }
    }

    return BaseViewer::eventFilter(watched, event);
}
Esempio n. 8
0
void GraphView::moveTo(const QModelIndex &index)
{
    QTableView *view = qobject_cast<QTableView *>(QObject::sender());
    GraphTableProxyModel *tableProxy = static_cast<GraphTableProxyModel *>(view->model());
    if (tableProxy == NULL)
    {
        qDebug() << "[GraphView]: can't cast sender of signal";
        return;
    }
    QVariant var = tableProxy->data(QModelIndex(), objectIdListRole);
    mapIntToInt idMap = qvariant_cast<mapIntToInt>(var);
    foreach(int id, idMap)
    {
        qDebug() << "[GraphView]: (table, model):(" << id << "," << idMap[id] << ")";
    }

    int modelRow = idMap.value(index.row(), -1);
    ObjectVisual *obj = scene()->getObjectById(modelRow);
    if (obj != NULL)
    {
        qDebug() << "[GraphView]: moving to #" << modelRow <<
                    "(tabled as#" << index.row() << ")=" << obj;
        centerOn(obj);
    }
}
Esempio n. 9
0
void VotingPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;
    // When this is a tab/widget and not a model dialog, ignore "done"
    /* if(mode == ForEditing) */
    /*     return; */

    // Figure out which address was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(VotingTableModel::Address);

    foreach (QModelIndex index, indexes)
    {
        QVariant address = table->model()->data(index);
        returnValue = address.toString();
    }
Esempio n. 10
0
void InvoicePage::on_deleteButton_clicked()
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;
    QModelIndexList indexes = table->selectionModel()->selectedRows();
    if(!indexes.isEmpty())
    {
        table->model()->removeRow(indexes.at(0).row());
    }
}
Esempio n. 11
0
void AddressBookPage::done(int retval)
{
    QTableView *table = ui->tableView;
    if(!table->selectionModel() || !table->model())
        return;

    // Figure out which address was selected, and return it
    QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);

    for (const QModelIndex& index : indexes) {
        QVariant address = table->model()->data(index);
        returnValue = address.toString();
    }

    if(returnValue.isEmpty())
    {
        // If no address entry selected, return rejected
        retval = Rejected;
    }

    QDialog::done(retval);
}
Esempio n. 12
0
void MessagePage::selectionChanged()
{
    // Set button states based on selected tab and selection
    QTableView *table = ui->tableView;
    if(!table->selectionModel())
        return;

    if(table->selectionModel()->hasSelection())
    {
        replyAction->setEnabled(true);
        copyFromAddressAction->setEnabled(true);
        copyToAddressAction->setEnabled(true);
        deleteAction->setEnabled(true);

        ui->copyFromAddressButton->setEnabled(true);
        ui->copyToAddressButton->setEnabled(true);
        ui->deleteButton->setEnabled(true);

        ui->newButton->setEnabled(false);
        ui->newButton->setVisible(false);
        ui->sendButton->setEnabled(true);
        ui->sendButton->setVisible(true);
        ui->messageEdit->setVisible(true);

        ui->tableView->hide();

        // Figure out which message was selected
        QModelIndexList labelColumn       = table->selectionModel()->selectedRows(MessageModel::Label);
        QModelIndexList addressFromColumn = table->selectionModel()->selectedRows(MessageModel::FromAddress);
        QModelIndexList addressToColumn   = table->selectionModel()->selectedRows(MessageModel::ToAddress);
        QModelIndexList typeColumn        = table->selectionModel()->selectedRows(MessageModel::Type);

        int type;

        foreach (QModelIndex index, typeColumn)
            type = table->model()->data(index).toInt();

        foreach (QModelIndex index, labelColumn)
            ui->contactLabel->setText(table->model()->data(index).toString());

        foreach (QModelIndex index, addressFromColumn)
            if(type == MessageTableEntry::Sent)
                replyFromAddress = table->model()->data(index).toString();
            else
                replyToAddress = table->model()->data(index).toString();

        foreach (QModelIndex index, addressToColumn)
            if(type == MessageTableEntry::Sent)
                replyToAddress = table->model()->data(index).toString();
            else
                replyFromAddress = table->model()->data(index).toString();

        QString filter = replyToAddress;

        //QString filter = replyFromAddress;
        ui->messageDetails->show();
        ui->listConversation->setCurrentIndex(model->proxyModel->index(0, 0, QModelIndex()));
    }
Esempio n. 13
0
CoverArtDelegate::CoverArtDelegate(QObject *parent)
        : QStyledItemDelegate(parent),
          m_bOnlyCachedCover(false),
          m_iCoverColumn(-1),
          m_iCoverSourceColumn(-1),
          m_iCoverTypeColumn(-1),
          m_iCoverLocationColumn(-1),
          m_iCoverHashColumn(-1),
          m_iTrackLocationColumn(-1),
          m_iIdColumn(-1) {
    // This assumes that the parent is wtracktableview
    connect(parent, SIGNAL(onlyCachedCoverArt(bool)),
            this, SLOT(slotOnlyCachedCoverArt(bool)));

    CoverArtCache* pCache = CoverArtCache::instance();
    if (pCache) {
        connect(pCache, SIGNAL(coverFound(const QObject*, const CoverInfo&,
                                          QPixmap, bool)),
                this, SLOT(slotCoverFound(const QObject*, const CoverInfo&,
                                          QPixmap, bool)));
    }

    TrackModel* pTrackModel = NULL;
    QTableView* pTableView = NULL;
    if (QTableView *tableView = qobject_cast<QTableView*>(parent)) {
        pTableView = tableView;
        pTrackModel = dynamic_cast<TrackModel*>(pTableView->model());
    }

    if (pTrackModel) {
        m_iCoverColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_COVERART);
        m_iCoverSourceColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_COVERART_SOURCE);
        m_iCoverTypeColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_COVERART_TYPE);
        m_iCoverHashColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_COVERART_HASH);
        m_iCoverLocationColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_COVERART_LOCATION);
        m_iTrackLocationColumn = pTrackModel->fieldIndex(
            TRACKLOCATIONSTABLE_LOCATION);
        m_iIdColumn = pTrackModel->fieldIndex(
            LIBRARYTABLE_ID);
    }
}
Esempio n. 14
0
//! [4a]
void AddressWidget::editEntry()
{
    QTableView *temp = static_cast<QTableView*>(currentWidget());
    QSortFilterProxyModel *proxy = static_cast<QSortFilterProxyModel*>(temp->model());
    QItemSelectionModel *selectionModel = temp->selectionModel();

    QModelIndexList indexes = selectionModel->selectedRows();
    QString name;
    QString address;
    int row = -1;

    foreach (QModelIndex index, indexes) {
        row = proxy->mapToSource(index).row();
        QModelIndex nameIndex = table->index(row, 0, QModelIndex());
        QVariant varName = table->data(nameIndex, Qt::DisplayRole);
        name = varName.toString();

        QModelIndex addressIndex = table->index(row, 1, QModelIndex());
        QVariant varAddr = table->data(addressIndex, Qt::DisplayRole);
        address = varAddr.toString();
    }
Esempio n. 15
0
// Auto-connected to actionCut's signal triggered()
void MainWindow::on_actionCut_triggered()
{
    QWidget *widget = ui->tabWidget->currentWidget();
    QTableView *tableView = qobject_cast<QTableView *>(widget);
    if (tableView)
    {
//         QModelIndexList selection = tableView->selectionModel()->selectedIndexes();
//         QSet<int> rows;
//         Q_FOREACH (QModelIndex index, selection)
//         {
//             rows.insert(index.row());
//         }
//         qDebug() << "Removing number of rows:" << rows.size();
        QModelIndex index = tableView->currentIndex();
        if (!index.isValid())
            return;
        QAbstractItemModel *model = tableView->model();
        Q_ASSERT(model);
        model->removeRow(index.row());
    }
}
Esempio n. 16
0
void AddressOverviewWindow::editEntry()
{
    QTableView *temp = static_cast<QTableView*>(ui->AddressesTableView);
    QSortFilterProxyModel *proxy = static_cast<QSortFilterProxyModel*>(temp->model());
    QItemSelectionModel *selectionModel = temp->selectionModel();
    QModelIndexList indexes = selectionModel->selectedRows();
    QModelIndex index, i;
    QString firstName;
    QString lastName;
    QString address;
    QString city;
    QString zipCode;
    int row = -1;

    foreach (index, indexes) {
        row = proxy->mapToSource(index).row();
        i = model->index(row, 0, QModelIndex());
        QVariant varFirstName = model->data(i, Qt::DisplayRole);
        firstName = varFirstName.toString();

        i = model->index(row, 1, QModelIndex());
        QVariant varLastName = model->data(i, Qt::DisplayRole);
        lastName = varLastName.toString();

        i = model->index(row, 2, QModelIndex());
        QVariant varAddr = model->data(i, Qt::DisplayRole);
        address = varAddr.toString();

        i = model->index(row, 3, QModelIndex());
        QVariant varCity = model->data(i, Qt::DisplayRole);
        city = varCity.toString();

        i = model->index(row, 4, QModelIndex());
        QVariant varZip = model->data(i, Qt::DisplayRole);
        zipCode = varZip.toString();
    }
void Button::placeButton()
{
    QTableView* table = qobject_cast<QTableView*>(this->parent());
    if (!table)
    {
        setVisible(false);
        return ;
    }

    if (_point.isNull())
    {
        QSize s = table->viewport()->size();
        //qDebug() << s;
        _point = QPoint(s.width(),s.height());
    }

    QAbstractItemModel* model = table->model();
    if (!model)
        return;

    int n,m,bsize1,bsize2,offset1,offset2,point1,point2;
    getSizes(table,model,&m,&n,&bsize1,&bsize2,&point1,&point2,&offset1,&offset2);

    int coord1;
    int coord2 = 0;

    int sizes[m];
    if (_orientation == Qt::Horizontal)
    {
        for (int i=0;i<m;i++)
            sizes[i] = table->columnWidth(i);
        for (int i=0;i<n;i++)
            coord2 += table->rowHeight(i);
    }
    else
    {
        for (int i=0;i<m;i++)
            sizes[i] = table->rowHeight(i);
        for (int i=0;i<n;i++)
            coord2 += table->columnWidth(i);
    }

    if (_type == InsertRemove::Insert)
        nearestBorder(_policy,point1+offset1,sizes,m,&_modelIndex,&coord1);
    else // _type == InsertRemove::Remove
        nearestMiddle(_policy,point1+offset1,sizes,m,&_modelIndex,&coord1);


    coord1 -= bsize1 / 2;

    QSize vp = usefulWidgetSize(table);
    QPoint sh = table->viewport()->mapToParent(QPoint(0,0)); //насколько viewport меньше table

    if (_orientation == Qt::Horizontal)
    {
        if (coord2 - offset2 + bsize2 + sh.y() > vp.height())
            coord2 = vp.height() - bsize2 + offset2 - sh.y();
    }
    else
    {
        if (coord2 - offset2 + bsize2 + sh.x() > vp.width())
            coord2 = vp.width() - bsize2 + offset2 - sh.x();
    }

    if (_orientation == Qt::Horizontal)
    {
        QPoint p = table->viewport()->mapToParent(QPoint(coord1 - offset1,coord2 - offset2));
        setGeometry(QRect(p,size()));
    }
    else
    {
        QPoint p = table->viewport()->mapToParent(QPoint(coord2 - offset2,coord1 - offset1));
        setGeometry(QRect(p,size()));
    }

    if (_type == InsertRemove::Insert)
    {
        setVisible(_modelIndex>=0);
    }
    else
    {
        setVisible((_policy & InsertRemove::RemoveAllowed) && (_modelIndex>-1));
    }

}
Esempio n. 18
0
    OLD_MAIN(QWidget* pParent = nullptr)
        : QMainWindow(pParent)
    {
        Q_INIT_RESOURCE(Resources);

        // Settings persistence
        ReadSettings();

        // Appearance LUT
        PlayerApperances appearances;

        // Build player table model from file
        PlayerTableModel* playerTableModel = new PlayerTableModel(this);
        playerTableModel->LoadHittingProjections(appearances);
        playerTableModel->LoadPitchingProjections(appearances);
        playerTableModel->CalculateHittingScores();
        playerTableModel->CalculatePitchingScores();
        playerTableModel->InitializeTargetValues();

        // Draft delegate
        DraftDelegate* draftDelegate = new DraftDelegate(playerTableModel);
        LinkDelegate* linkDelegate = new LinkDelegate(this);
        TagDelegate* tagDelegate = new TagDelegate(this);

        // Hitter sort-model
        PlayerSortFilterProxyModel* hitterSortFilterProxyModel = new PlayerSortFilterProxyModel(Player::Hitter);
        hitterSortFilterProxyModel->setSourceModel(playerTableModel);
        hitterSortFilterProxyModel->setSortRole(PlayerTableModel::RawDataRole);

        // Hitter table view
        QTableView* hitterTableView = MakeTableView(hitterSortFilterProxyModel, true, PlayerTableModel::COLUMN_Z);
        hitterTableView->setItemDelegateForColumn(FindColumn(hitterSortFilterProxyModel, PlayerTableModel::COLUMN_DRAFT_BUTTON), draftDelegate);
        hitterTableView->setItemDelegateForColumn(FindColumn(hitterSortFilterProxyModel, PlayerTableModel::COLUMN_ID_LINK), linkDelegate);
        hitterTableView->setItemDelegateForColumn(FindColumn(hitterSortFilterProxyModel, PlayerTableModel::COLUMN_FLAG), tagDelegate);
        hitterTableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);

        // Context menu
        QMenu* contextMenu = new QMenu();
        contextMenu->addAction("&Remove Player");

        // Apply to hitter table view
        hitterTableView->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(hitterTableView, &QWidget::customContextMenuRequested, [=](const QPoint& pos) {
            QPoint globalPos = hitterTableView->mapToGlobal(pos);
            QAction* selectedItem = contextMenu->exec(globalPos);
            if (selectedItem) {
                auto proxyIndex = hitterTableView->indexAt(pos);
                auto srcIndex = hitterSortFilterProxyModel->mapToSource(proxyIndex);
                playerTableModel->RemovePlayer(srcIndex.row());
            }
        });

        // Pitcher sort-model
        PlayerSortFilterProxyModel* pitcherSortFilterProxyModel = new PlayerSortFilterProxyModel(Player::Pitcher);
        pitcherSortFilterProxyModel->setSourceModel(playerTableModel);
        pitcherSortFilterProxyModel->setSortRole(PlayerTableModel::RawDataRole);
        
        // Pitcher table view
        QTableView* pitcherTableView = MakeTableView(pitcherSortFilterProxyModel, true, PlayerTableModel::COLUMN_Z);
        pitcherTableView->setItemDelegateForColumn(FindColumn(pitcherSortFilterProxyModel, PlayerTableModel::COLUMN_DRAFT_BUTTON), draftDelegate);
        pitcherTableView->setItemDelegateForColumn(FindColumn(pitcherSortFilterProxyModel, PlayerTableModel::COLUMN_ID_LINK), linkDelegate);
        pitcherTableView->setItemDelegateForColumn(FindColumn(pitcherSortFilterProxyModel, PlayerTableModel::COLUMN_FLAG), tagDelegate);
        pitcherTableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);

        // Top/Bottom splitter
        QSplitter* topBottomSplitter = new QSplitter(Qt::Vertical);
        topBottomSplitter->setContentsMargins(5, 5, 5, 5);

        // Hitter/Pitcher tab View
        enum PlayerTableTabs { Hitters, Pitchers, Unknown };
        QTabWidget* hitterPitcherTabs = new QTabWidget(this);
        hitterPitcherTabs->insertTab(PlayerTableTabs::Hitters, hitterTableView, "Hitters");
        hitterPitcherTabs->insertTab(PlayerTableTabs::Pitchers, pitcherTableView, "Pitchers");
        topBottomSplitter->addWidget(hitterPitcherTabs);

        // Tab lookup helper
        auto CaterogyToTab = [](uint32_t catergory) 
        {
            switch (catergory)
            {
            case Player::Hitter:
                return PlayerTableTabs::Hitters;
            case Player::Pitcher:
                return PlayerTableTabs::Pitchers;
            default:
                return PlayerTableTabs::Unknown;
            }
        };

        // Drafted filter action
        QAction* filterDrafted = new QAction(this);
        connect(filterDrafted, &QAction::toggled, hitterSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterDrafted);
        connect(filterDrafted, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterDrafted);
        filterDrafted->setText(tr("Drafted"));
        filterDrafted->setToolTip("Toggle Drafted Players");
        filterDrafted->setCheckable(true);
        filterDrafted->toggle();

        QAction* filterReplacement = new QAction(this);
        connect(filterReplacement, &QAction::toggled, hitterSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterReplacement);
        connect(filterReplacement, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterReplacement);
        filterReplacement->setText(tr("($1)"));
        filterReplacement->setToolTip("Toggle replacements players with value under $1");
        filterReplacement->setCheckable(true);
        filterReplacement->toggle();

        // NL filter action
        QAction* filterNL = new QAction(this);
        connect(filterNL, &QAction::toggled, hitterSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterNL);
        connect(filterNL, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterNL);
        filterNL->setText(tr("NL"));
        filterNL->setToolTip("Toggle National Leauge");
        filterNL->setCheckable(true);
        filterNL->toggle();

        // AL filter action
        QAction* filterAL = new QAction(this);
        connect(filterAL, &QAction::toggled, hitterSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterAL);
        connect(filterAL, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterAL);
        filterAL->setText(tr("AL"));
        filterAL->setToolTip("Toggle American Leauge");
        filterAL->setCheckable(true);
        filterAL->toggle();

        // FA filter action
        QAction* filterFA = new QAction(this);
        connect(filterFA, &QAction::toggled, hitterSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterFA);
        connect(filterFA, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterFA);
        filterFA->setText(tr("FA"));
        filterFA->setToolTip("Toggle Free Agents");
        filterFA->setCheckable(true);
        filterAL->toggle();
        filterAL->toggle();

        // General filter group
        QActionGroup* generalFilters = new QActionGroup(this);
        generalFilters->addAction(filterAL);
        generalFilters->addAction(filterNL);
        generalFilters->addAction(filterFA);
        generalFilters->setExclusive(false);

        // Starter filter action
        QAction* filterStarter = new QAction(this);
        connect(filterStarter, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterSP);
        filterStarter->setText(tr("SP"));
        filterStarter->setToolTip("Toggle Starting Pitchers");
        filterStarter->setCheckable(true);
        filterStarter->toggle();

        // Relief filter action
        QAction* filterRelief = new QAction(this);
        connect(filterRelief, &QAction::toggled, pitcherSortFilterProxyModel, &PlayerSortFilterProxyModel::OnFilterRP);
        filterRelief->setText(tr("RP"));
        filterRelief->setToolTip("Toggle Relief Pitchers");
        filterRelief->setCheckable(true);
        filterRelief->toggle();

        // Pitching filter group
        QActionGroup* pitchingFilters = new QActionGroup(this);
        pitchingFilters->addAction(filterStarter);
        pitchingFilters->addAction(filterRelief);
        pitchingFilters->setExclusive(false);

        // Hitting filter group
        QActionGroup* hittingFilters = new QActionGroup(this);
        hittingFilters->setExclusive(false);

        // Filter helper
        auto MakeHitterFilter = [=](QString text, QString toolTip, const auto& onFilterFn) -> QAction* 
        {
            QAction* action = new QAction(this);
            connect(action, &QAction::toggled, hitterSortFilterProxyModel, onFilterFn);
            action->setText(text);
            action->setToolTip(toolTip);
            action->setCheckable(true);
            action->toggle();
            hittingFilters->addAction(action);

            return action;
        };

        // Hitter filters
        QAction* filterC  = MakeHitterFilter("C",  "Filter Catchers",           &PlayerSortFilterProxyModel::OnFilterC);
        QAction* filter1B = MakeHitterFilter("1B", "Filter 1B",                 &PlayerSortFilterProxyModel::OnFilter1B);
        QAction* filter2B = MakeHitterFilter("2B", "Filter 2B",                 &PlayerSortFilterProxyModel::OnFilter2B);
        QAction* filterSS = MakeHitterFilter("SS", "Filter SS",                 &PlayerSortFilterProxyModel::OnFilterSS);
        QAction* filter3B = MakeHitterFilter("3B", "Filter 3B",                 &PlayerSortFilterProxyModel::OnFilter3B);
        QAction* filterOF = MakeHitterFilter("OF", "Filter Outfielders",        &PlayerSortFilterProxyModel::OnFilterOF);
        QAction* filterCI = MakeHitterFilter("CI", "Filter Corner Infielders",  &PlayerSortFilterProxyModel::OnFilterCI);
        QAction* filterMI = MakeHitterFilter("MI", "Filter Middle Infielders",  &PlayerSortFilterProxyModel::OnFilterMI);
        QAction* filterDH = MakeHitterFilter("DH", "Filter Designated Hitters", &PlayerSortFilterProxyModel::OnFilterDH);
        QAction* filterU  = MakeHitterFilter("U",  "Filter Utility",            &PlayerSortFilterProxyModel::OnFilterU);

        // Menu spacer
        QWidget* spacer = new QWidget(this);
        spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        // Completion Widget
        QCompleter* completer = new QCompleter(this);
        completer->setModel(playerTableModel);
        completer->setCompletionColumn(PlayerTableModel::COLUMN_NAME);
        completer->setFilterMode(Qt::MatchContains);
        completer->setCaseSensitivity(Qt::CaseInsensitive);

        // Select
        auto HighlightPlayerInTable = [=](const QModelIndex& srcIdx)
        {
            // Lookup catergory
            auto catergoryIdx = srcIdx.model()->index(srcIdx.row(), PlayerTableModel::COLUMN_CATERGORY);
            auto catergory = srcIdx.model()->data(catergoryIdx).toUInt();

            // Change to tab
            hitterPitcherTabs->setCurrentIndex(CaterogyToTab(catergory));

            // Select row
            if (catergory == Player::Catergory::Hitter) {
                auto proxyModel = dynamic_cast<QSortFilterProxyModel*>(hitterTableView->model());
                auto proxyIdx = proxyModel->mapFromSource(srcIdx);
                hitterTableView->selectRow(proxyIdx.row());
                hitterTableView->setFocus();
            } else if (catergory == Player::Catergory::Pitcher) {
                auto proxyModel = dynamic_cast<QSortFilterProxyModel*>(pitcherTableView->model());
                auto proxyIdx = proxyModel->mapFromSource(srcIdx);
                pitcherTableView->selectRow(proxyIdx.row());
                pitcherTableView->setFocus();
            }
        };

        // Select the target 
        connect(completer, static_cast<void (QCompleter::*)(const QModelIndex&)>(&QCompleter::activated), [=](const QModelIndex& index) {

            // Get player index
            QAbstractProxyModel* proxyModel = dynamic_cast<QAbstractProxyModel*>(completer->completionModel());
            auto srcIdx = proxyModel->mapToSource(index);
            
            // Highlight this player
            HighlightPlayerInTable(srcIdx);
        });


        // Search widget
        QLineEdit* playerSearch = new QLineEdit(this);
        playerSearch->setCompleter(completer);

        // Main toolbar
        QToolBar* toolbar = new QToolBar("Toolbar");
        toolbar->addWidget(new QLabel(" Status: ", this));
        toolbar->addActions(QList<QAction*>{filterDrafted, filterReplacement});
        toolbar->addSeparator();
        toolbar->addWidget(new QLabel(" Leagues: ", this));
        toolbar->addActions(QList<QAction*>{filterAL, filterNL, filterFA});
        toolbar->addSeparator();
        toolbar->addWidget(new QLabel(" Positions: ", this));
        toolbar->addActions(QList<QAction*>{filterStarter, filterRelief});
        toolbar->addActions(QList<QAction*>{filterC, filter1B, filter2B, filterSS, filter3B, filterOF, filterCI, filterMI, filterDH, filterU});
        toolbar->addWidget(spacer);
        toolbar->addWidget(new QLabel("Player Search: ", this));
        toolbar->addWidget(playerSearch);
        toolbar->setFloatable(false);
        toolbar->setMovable(false);
        QMainWindow::addToolBar(toolbar);

        // Helper to adjust filters
        auto ToggleFilterGroups = [=](int index)
        {
            switch (index)
            {
            case uint32_t(PlayerTableTabs::Hitters):
                pitchingFilters->setVisible(false);
                hittingFilters->setVisible(true);
                break;
            case uint32_t(PlayerTableTabs::Pitchers):
                pitchingFilters->setVisible(true);
                hittingFilters->setVisible(false);
                break;
            default:
                break;
            }
        };

        // Set default filter group
        ToggleFilterGroups(hitterPitcherTabs->currentIndex());

        //---------------------------------------------------------------------
        // Bottom Section
        //---------------------------------------------------------------------

        // Owner widget
        QHBoxLayout* ownersLayout = new QHBoxLayout(this);
        ownersLayout->setSizeConstraint(QLayout::SetNoConstraint);

        // Owner models
        std::vector<OwnerSortFilterProxyModel*> vecOwnerSortFilterProxyModels;

        // Owner labels
        QList<QLabel*>* pVecOwnerLabels;
        pVecOwnerLabels = new QList<QLabel*>();
        pVecOwnerLabels->append(new QLabel("--"));
        for (auto i = 1u; i <= DraftSettings::Get().OwnerCount; i++) {
            pVecOwnerLabels->append(new QLabel(DraftSettings::Get().OwnerNames[i]));
        }

        // Update label helper
        auto UpdateOwnerLabels = [=]() {
            for (auto i = 1u; i <= DraftSettings::Get().OwnerCount; i++) {
                pVecOwnerLabels->at(i)->setText(DraftSettings::Get().OwnerNames[i]);
            }
        };

        // Initialize
        UpdateOwnerLabels();

        // Loop owners
        for (uint32_t ownerId = 1; ownerId <= DraftSettings::Get().OwnerCount; ownerId++) {

            // V-Layout per owner
            QVBoxLayout* perOwnerLayout = new QVBoxLayout(this);
            ownersLayout->addLayout(perOwnerLayout);
            perOwnerLayout->setSizeConstraint(QLayout::SetNoConstraint);

            // Proxy model for this owner
            OwnerSortFilterProxyModel* ownerSortFilterProxyModel = new OwnerSortFilterProxyModel(ownerId, playerTableModel, this);
            vecOwnerSortFilterProxyModels.push_back(ownerSortFilterProxyModel);

            // Owner name label
            pVecOwnerLabels->at(ownerId)->setAlignment(Qt::AlignCenter);
            perOwnerLayout->addWidget(pVecOwnerLabels->at(ownerId));

            // Per-owner roster table view
            const uint32_t tableWidth = 225;
            QTableView* ownerRosterTableView = MakeTableView(ownerSortFilterProxyModel, true, 0);
            ownerRosterTableView->setMinimumSize(tableWidth, 65);
            ownerRosterTableView->setMaximumSize(tableWidth, 4096);
            ownerRosterTableView->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
            perOwnerLayout->addWidget(ownerRosterTableView);

            // XXX: This should be a form layout...
            QGridLayout* ownerSummaryGridLayout = new QGridLayout(this);
            ownerSummaryGridLayout->setSpacing(0);
            ownerSummaryGridLayout->addWidget(MakeLabel("Budget: "),     0, 0);
            ownerSummaryGridLayout->addWidget(MakeLabel("# Hitters: "),  1, 0);
            ownerSummaryGridLayout->addWidget(MakeLabel("# Pitchers: "), 2, 0);
            ownerSummaryGridLayout->addWidget(MakeLabel("Max Bid: "),    3, 0);

            QLabel* budgetLabel = MakeLabel();
            QLabel* numHittersLabel = MakeLabel();
            QLabel* numPitchersLabel = MakeLabel();
            QLabel* maxBidLabel = MakeLabel();

            // Helper
            auto UpdateLabels = [=]()
            {
                budgetLabel->setText(QString("$%1").arg(ownerSortFilterProxyModel->GetRemainingBudget()));
                numHittersLabel->setText(QString("%1 / %2").arg(ownerSortFilterProxyModel->Count(Player::Hitter)).arg(DraftSettings::Get().HitterCount));
                numPitchersLabel->setText(QString("%1 / %2").arg(ownerSortFilterProxyModel->Count(Player::Pitcher)).arg(DraftSettings::Get().PitcherCount));
                maxBidLabel->setText(QString("$%1").arg(ownerSortFilterProxyModel->GetMaxBid()));
            };

            // Update labels when a draft event happens
            connect(playerTableModel, &PlayerTableModel::DraftedEnd, [=]() {
                UpdateLabels();
            });

            UpdateLabels();

            ownerSummaryGridLayout->addWidget(budgetLabel,      0, 1);
            ownerSummaryGridLayout->addWidget(numHittersLabel,  1, 1);
            ownerSummaryGridLayout->addWidget(numPitchersLabel, 2, 1);
            ownerSummaryGridLayout->addWidget(maxBidLabel,      3, 1);

            QSpacerItem* spacer = new QSpacerItem(1, 1, QSizePolicy::Preferred, QSizePolicy::Preferred);

            ownerSummaryGridLayout->addItem(spacer, 0, 2);
            ownerSummaryGridLayout->addItem(spacer, 1, 2);
            ownerSummaryGridLayout->addItem(spacer, 2, 2);
            ownerSummaryGridLayout->addItem(spacer, 3, 2);
            perOwnerLayout->addLayout(ownerSummaryGridLayout);

            perOwnerLayout->addSpacerItem(spacer);
        }

        // Owner widget
        QWidget* scrollAreaWidgetContents = new QWidget(this);
        scrollAreaWidgetContents->setLayout(ownersLayout);
        scrollAreaWidgetContents->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

        // Owner scroll area
        QScrollArea* ownerScrollArea = new QScrollArea(this);
        ownerScrollArea->setWidget(scrollAreaWidgetContents);
        ownerScrollArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
        ownerScrollArea->setBackgroundRole(QPalette::Light);
        ownerScrollArea->setFrameShape(QFrame::NoFrame);
        ownerScrollArea->setWidgetResizable(true);

        // Target value widget
        QWidget* targetValueWidget = new QWidget(this);
        QFormLayout* targetValueLayout = new QFormLayout(this);
        targetValueWidget->setLayout(targetValueLayout);
        auto values = {
            PlayerTableModel::COLUMN_AVG,
            PlayerTableModel::COLUMN_HR,
            PlayerTableModel::COLUMN_R,
            PlayerTableModel::COLUMN_RBI,
            PlayerTableModel::COLUMN_SB,
            PlayerTableModel::COLUMN_SO,
            PlayerTableModel::COLUMN_ERA,
            PlayerTableModel::COLUMN_WHIP,
            PlayerTableModel::COLUMN_W,
            PlayerTableModel::COLUMN_SV,
        };
        for (auto value : values) {
            auto name = playerTableModel->headerData(value, Qt::Horizontal, Qt::DisplayRole).toString();
            auto target = QString::number(playerTableModel->GetTargetValue(value), 'f', 3);
            targetValueLayout->addRow(name, new QLabel(target));
        }

        // Player scatter plot
        PlayerScatterPlotChart* chartView = new PlayerScatterPlotChart(playerTableModel, hitterSortFilterProxyModel, this);
        connect(hitterSortFilterProxyModel,  &QSortFilterProxyModel::layoutChanged, chartView, &PlayerScatterPlotChart::Update);
        connect(pitcherSortFilterProxyModel, &QSortFilterProxyModel::layoutChanged, chartView, &PlayerScatterPlotChart::Update);
        connect(playerTableModel, &QAbstractItemModel::dataChanged, chartView, &PlayerScatterPlotChart::Update);

        // Summary view
        SummaryWidget* summary = new SummaryWidget(playerTableModel, vecOwnerSortFilterProxyModels, this);

        // Bottom tabs
        enum BottomSectionTabs { Rosters, Summary, Targets, ChartView, Log };
        QTabWidget* bottomTabs = new QTabWidget(this);
        topBottomSplitter->addWidget(bottomTabs);
        bottomTabs->insertTab(BottomSectionTabs::Rosters, ownerScrollArea, "Rosters");
        bottomTabs->insertTab(BottomSectionTabs::Summary, summary, "Summary");
        bottomTabs->insertTab(BottomSectionTabs::Targets, targetValueWidget, "Targets");
        bottomTabs->insertTab(BottomSectionTabs::ChartView, chartView, "Scatter Chart");
        bottomTabs->insertTab(BottomSectionTabs::Log, GlobalLogger::Get(), "Log");

        // Make top section 3x the size of the bottom
        topBottomSplitter->setStretchFactor(0, 3);
        topBottomSplitter->setStretchFactor(1, 1);

        //----------------------------------------------------------------------
        // Connections
        //----------------------------------------------------------------------

        // Connect tab filters
        connect(hitterPitcherTabs, &QTabWidget::currentChanged, this, [=](int index) {
            
            // Update filters
            ToggleFilterGroups(index);

            // Update chart view
            switch (index)
            {
            case PlayerTableTabs::Hitters:
                chartView->SetProxyModel(hitterSortFilterProxyModel);
                break;
            case PlayerTableTabs::Pitchers:
                chartView->SetProxyModel(pitcherSortFilterProxyModel);
                break;
            default:
                break;
            }
        });

        // Connect chart click
        connect(chartView, &PlayerScatterPlotChart::PlayerClicked, this, [=](const QModelIndex& index) {
            HighlightPlayerInTable(index);
        });
        
        // Connect summary model
        connect(playerTableModel, &PlayerTableModel::DraftedEnd, summary, &SummaryWidget::OnDraftedEnd);

        //----------------------------------------------------------------------
        // Main
        //----------------------------------------------------------------------

        // Set as main window
        QMainWindow::setCentralWidget(topBottomSplitter);

        // Create main menu bar
        QMenuBar* mainMenuBar = new QMenuBar();
        QMainWindow::setMenuBar(mainMenuBar);
        
        // Main Menu > File menu
        QMenu* fileMenu = mainMenuBar->addMenu("&File");

        // File dialog helper
        auto GetFileDialog = [&](QFileDialog::AcceptMode mode) -> QFileDialog*
        {
            QFileDialog* dialog = new QFileDialog(this);
            dialog->setWindowModality(Qt::WindowModal);
            dialog->setAcceptMode(mode);
            dialog->setNameFilter("CSV files (*.csv)");
            return dialog;
        };

        // Ask for the save location 
        auto SetSaveAsFile = [=]()
        {
            QStringList files;
            auto dialog = GetFileDialog(QFileDialog::AcceptSave);
            if (dialog->exec()) {
                files = dialog->selectedFiles();
            } else {
                return false;
            }
            m_currentFile = files.at(0);
            return true;
        };

        // Update title bar
        auto UpdateApplicationName = [this]()
        {
            auto name = QString("fbb -- %1").arg(QFileInfo(m_currentFile).fileName());
            QCoreApplication::setApplicationName(name);
            setWindowTitle(name);
        };

        // Main Menu > File menu > Save action
        QAction* saveResultsAction = new QAction("&Save Results", this);
        connect(saveResultsAction, &QAction::triggered, [=](bool checked) {
            if (m_currentFile.isEmpty()) {
                SetSaveAsFile();
            }
            GlobalLogger::AppendMessage(QString("Saving file: %1...").arg(m_currentFile));
            UpdateApplicationName();
            return playerTableModel->SaveDraftStatus(m_currentFile);
        });
        fileMenu->addAction(saveResultsAction);

        // Main Menu > File menu > Save As action
        QAction* saveResultsAsAction = new QAction("Save Results &As...", this);
        connect(saveResultsAsAction, &QAction::triggered, [=](bool checked) {
            SetSaveAsFile();
            GlobalLogger::AppendMessage(QString("Saving file: %1...").arg(m_currentFile));
            UpdateApplicationName();
            return playerTableModel->SaveDraftStatus(m_currentFile);
        });
        fileMenu->addAction(saveResultsAsAction);
        
        // Main Menu > File menu > Load action
        QAction* loadResultsAction = new QAction("&Load Results...", this);
        connect(loadResultsAction, &QAction::triggered, [=](bool checked) {
            auto dialog = GetFileDialog(QFileDialog::AcceptOpen);
            QStringList files;
            if (dialog->exec()) {
                files = dialog->selectedFiles();
            } else {
                return false;
            }
            m_currentFile = files.at(0);
            GlobalLogger::AppendMessage(QString("Loading file: %1...").arg(m_currentFile));
            UpdateApplicationName();
            return playerTableModel->LoadDraftStatus(m_currentFile);
        });
        fileMenu->addAction(loadResultsAction);

        // Main Menu > File menu
        QMenu* settingsMenu = mainMenuBar->addMenu("&Settings");

        // Main Menu > Settings menu > Options action
        QAction* settingsAction = new QAction("&Settings...", this);
        connect(settingsAction, &QAction::triggered, [=](bool checked) {
            DraftSettingsDialog draftSettingsDialog;
            if (draftSettingsDialog.exec()) {
                UpdateOwnerLabels();
            }
        });
        settingsMenu->addAction(settingsAction);

        // Main Menu > Settings menu > Options action
        QAction* demoDataAction = new QAction("&DemoData...", this);
        connect(demoDataAction, &QAction::triggered, [=](bool checked) {
            playerTableModel->DraftRandom();
        });
        settingsMenu->addAction(demoDataAction);

        // show me
        QMainWindow::show();
    }
Esempio n. 19
0
void MotionViewFunctionItemEditor::comboBoxCurrentIndexChanged(int /*idx*/)
{
	QTableView* view = m_delegate->view();
	m_delegate->setModelData(this, view->model(), view->currentIndex());
}
Esempio n. 20
0
void MotionViewDoubleItemEditor::spinnerValueChanged()
{
	QTableView* view = m_delegate->view();
	m_delegate->setModelData(this, view->model(), view->currentIndex());
}
Esempio n. 21
0
SimpleQTableViewWidthInterface::SimpleQTableViewWidthInterface(QTableView& tbl) : TableWidthInterface(tbl.model()->columnCount()), m_tbl(tbl), m_pModel(tbl.model())
{
    int nCols (m_pModel->columnCount());
    m_vbBold.resize(nCols);

    QFont font (m_tbl.font());
    font.setBold(true);
    QFontMetrics fontMetrics (font);

    QHeaderView* pHdr (tbl.horizontalHeader());

    for (int j = 0; j < nCols; ++j)
    {
        if (pHdr->isSectionHidden(j))
        {
            setFixedWidth(j, 0);
        }
        else
        {
            m_vnHdrWidth[j] = fontMetrics.width(m_pModel->headerData(j, Qt::Horizontal).toString()) + 8/*2*QApplication::style()->pixelMetric(QStyle::PM_DefaultFrameWidth)*/; // PM_DefaultFrameWidth is not THE thing to use, but it's one way to get some spacing for the header; (well it turned up to be too small, so it got replaced by 8; probably look at the source to see what should be used)
        }
    }
}
void Button::on_clicked()
{
    QTableView* table = qobject_cast<QTableView*>(this->parent());
    if (!table)
        return;

    QAbstractItemModel* model = table->model();
    if (!model)
        return;

    if (_type == InsertRemove::Insert)
    {
        if (_orientation == Qt::Horizontal)
            model->insertColumn(_modelIndex);
        else
            model->insertRow(_modelIndex);
    }
    else // _type == InsertRemove::Remove
    {
        if (_orientation == Qt::Horizontal)
            model->removeColumn(_modelIndex);
        else
            model->removeRow(_modelIndex);
    }
}