Example #1
0
int ctkDICOMModelTest2( int argc, char * argv [] )
{
  QApplication app(argc, argv);

  if (argc <= 2)
    {
    std::cerr << "Warning, no sql file given. Test stops" << std::endl;
    std::cerr << "Usage: qctkDICOMModelTest1 <scratch.db> <dumpfile.sql>" << std::endl;
    return EXIT_FAILURE;
    }

  try
  {
    ctkDICOMDatabase myCTK( argv[1] );

    if (!myCTK.initializeDatabase(argv[2]))
    {
      std::cerr << "Error when initializing the data base: " << argv[2]
          << " error: " << myCTK.lastError().toStdString();
    }

    ctkDICOMModel model;
    model.setDatabase(myCTK.database());

    QWidget topLevel;
    QTreeView viewer;
    QHBoxLayout* layout = new QHBoxLayout;
    layout->addWidget(&viewer);
    topLevel.setLayout(layout);
    viewer.setModel(&model);

    QHeaderView* previousHeaderView = viewer.header();
    qDebug() << "previous: " << previousHeaderView->isHidden();
    ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, &viewer);
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    headerView->setClickable(previousHeaderView->isClickable());
    headerView->setMovable(previousHeaderView->isMovable());
#else
    headerView->setSectionsClickable(previousHeaderView->sectionsClickable());
    headerView->setSectionsMovable(previousHeaderView->sectionsMovable());
#endif
    headerView->setHighlightSections(previousHeaderView->highlightSections());
    headerView->checkableModelHelper()->setPropagateDepth(-1);
    headerView->checkableModelHelper()->setForceCheckability(true);
    viewer.setHeader(headerView);
    model.setHeaderData(0, Qt::Horizontal, Qt::Checked, Qt::CheckStateRole);
    qDebug() << "new: " << headerView->isHidden();
    topLevel.show();
    if (argc <= 3 || QString(argv[3]) != "-I")
      {
      QTimer::singleShot(200, &app, SLOT(quit()));
      }
    return app.exec();
  }
  catch (std::exception e)
    {
    std::cerr << "Error when opening the data base file: " << argv[1]
        << " error: " << e.what();
    return EXIT_FAILURE;
    }
}
Example #2
0
void pTreeComboBox::calculPopupGeometry()
{
    if ( !mView ) {
        return;
    }
    
    QStyle * const style = this->style();

    // set current item and select it
    view()->selectionModel()->setCurrentIndex( mCurrentIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
    QFrame* container = mFrame;
    QStyleOptionComboBox opt;
    initStyleOption( &opt );
    QRect listRect( style->subControlRect( QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxListBoxPopup, this ) );
    QRect screen = popupGeometry( QApplication::desktop()->screenNumber( this ) );
    QPoint below = mapToGlobal( listRect.bottomLeft() );
    int belowHeight = screen.bottom() -below.y();
    QPoint above = mapToGlobal( listRect.topLeft() );
    int aboveHeight = above.y() -screen.y();
    bool boundToScreen = !window()->testAttribute( Qt::WA_DontShowOnScreen );
    
    listRect.moveTopLeft( mapToGlobal( rect().bottomLeft() ) );
    listRect.setSize( QSize( 
        qMax( qMax( view()->viewport()->width(), mFrame->width() ), width() )
        ,
        qMax( view()->viewport()->height(), mFrame->height() )
    ) );

    const bool usePopup = style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this );
    {
        int listHeight = 0;
        int count = 0;
        QStack<QModelIndex> toCheck;
        toCheck.push( view()->rootIndex() );
#ifndef QT_NO_TREEVIEW
        QTreeView* treeView = qobject_cast<QTreeView*>( view() );
        if ( treeView && treeView->header() && !treeView->header()->isHidden() )
            listHeight += treeView->header()->height();
#endif
        while ( !toCheck.isEmpty() ) {
            QModelIndex parent = toCheck.pop();
            for ( int i = 0; i < model()->rowCount( parent ); ++i ) {
                QModelIndex idx = model()->index( i, mModelColumn, parent );
                if ( !idx.isValid() )
                    continue;
                listHeight += view()->visualRect( idx ).height();
#ifndef QT_NO_TREEVIEW
                if ( model()->hasChildren( idx ) && treeView && treeView->isExpanded( idx ) )
                    toCheck.push( idx );
#endif
                ++count;
                if ( !usePopup && count > mMaxVisibleItems ) {
                    toCheck.clear();
                    break;
                }
            }
        }
        listRect.setHeight( listHeight );
    }

    {
        // add the spacing for the grid on the top and the bottom;
        int heightMargin = 0;

        // add the frame of the container
        int marginTop, marginBottom;
        container->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        heightMargin += marginTop +marginBottom;

        //add the frame of the view
        view()->getContentsMargins( 0, &marginTop, 0, &marginBottom );
        marginTop += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->top*/;
        marginBottom += 0/*static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(view()))->bottom*/;
        heightMargin += marginTop +marginBottom;

        listRect.setHeight( listRect.height() +heightMargin );
    }

    // Add space for margin at top and bottom if the style wants it.
    if ( usePopup )
        listRect.setHeight( listRect.height() +style->pixelMetric( QStyle::PM_MenuVMargin, &opt, this ) *2 );

    // Make sure the popup is wide enough to display its contents.
    if ( usePopup ) {
        const int diff = sizeHint().width() /*d->computeWidthHint()*/ -width();
        if ( diff > 0 )
            listRect.setWidth( listRect.width() +diff );
    }

    //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
    container->layout()->activate();
    //takes account of the minimum/maximum size of the container
    listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                      .boundedTo(container->maximumSize()));

    // make sure the widget fits on screen
    if (boundToScreen) {
        if (listRect.width() > screen.width() )
            listRect.setWidth(screen.width());
        if (/*mapToGlobal(*/listRect/*.bottomRight())*/.x() > screen.right()) {
            below.setX(screen.x() + screen.width() - listRect.width());
            above.setX(screen.x() + screen.width() - listRect.width());
        }
        if (/*mapToGlobal(*/listRect/*.topLeft())*/.x() < screen.x() ) {
            below.setX(screen.x());
            above.setX(screen.x());
        }
    }

    if ( usePopup ) {
        // Position horizontally.
        listRect.moveLeft( above.x() );

        // Position vertically so the curently selected item lines up
        // with the combo box.
        /*const QRect currentItemRect = view()->visualRect( view()->currentIndex() );
        const int offset = listRect.top() -currentItemRect.top();
        listRect.moveTop( above.y() +offset -listRect.top() );*/

        // Clamp the listRect height and vertical position so we don't expand outside the
        // available screen geometry.This may override the vertical position, but it is more
        // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
        listRect.setHeight(height);
        if (boundToScreen) {
            if (listRect.top() < screen.top())
                listRect.moveTop(screen.top());
            if (listRect.bottom() > screen.bottom())
                listRect.moveBottom(screen.bottom());
        }
    } else if (!boundToScreen || listRect.height() <= belowHeight) {
        listRect.moveTopLeft(below);
    } else if (listRect.height() <= aboveHeight) {
        listRect.moveBottomLeft(above);
    } else if (belowHeight >= aboveHeight) {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
    } else {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
    }

#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
#ifndef QT_NO_IM
    if ( QInputContext *qic = inputContext() )
        qic->reset();
#endif
#endif
    QScrollBar* sb = view()->horizontalScrollBar();
    Qt::ScrollBarPolicy policy = view()->horizontalScrollBarPolicy();
    bool needHorizontalScrollBar = ( policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn ) && sb->minimum() < sb->maximum();
    if ( needHorizontalScrollBar ) {
        listRect.adjust( 0, 0, 0, sb->height() );
    }
    
    container->setGeometry( listRect );

#ifndef Q_WS_MAC
    const bool updatesEnabled = container->updatesEnabled();
#endif

#if defined( Q_WS_WIN ) && !defined( QT_NO_EFFECTS )
// FIXME Fix me ASAP
    /*bool scrollDown = ( listRect.topLeft() == below );
    if ( QApplication::isEffectEnabled( Qt::UI_AnimateCombo ) 
        && !style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) && !window()->testAttribute( Qt::WA_DontShowOnScreen ) )
        qScrollEffect( container, scrollDown ? QEffects::DownScroll : QEffects::UpScroll, 150 );*/
#endif

// Don't disable updates on Mac OS X. Windows are displayed immediately on this platform,
// which means that the window will be visible before the call to container->show() returns.
// If updates are disabled at this point we'll miss our chance at painting the popup 
// menu before it's shown, causing flicker since the window then displays the standard gray 
// background.
#ifndef Q_WS_MAC
    container->setUpdatesEnabled( false );
#endif

    container->raise();
    container->show();
    //container->updateScrollers();
    view()->setFocus();

    view()->scrollTo( view()->currentIndex(), style->styleHint( QStyle::SH_ComboBox_Popup, &opt, this ) ? QAbstractItemView::PositionAtCenter : QAbstractItemView::EnsureVisible );

#ifndef Q_WS_MAC
    container->setUpdatesEnabled( updatesEnabled );
#endif

    container->update();
#ifdef QT_KEYPAD_NAVIGATION
    if ( QApplication::keypadNavigationEnabled() )
        view()->setEditFocus( true );
#endif
}
Example #3
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //:/image/cat.jpg

    ui->setupUi(this);

    QString imagepath = ":/new/prefix1/folder.png";
    QPixmap image0(imagepath);
    QPixmap image = image0.scaled(QSize(100,100));
    qDebug() << image.size();
    QIcon myIcon =  QIcon(image);



    QSplitter *page= new QSplitter();

    //customer
    QList<QVariant> title;
    title<<"one"<<"two";

    QList<ItemObject*> values;
    GetData(values);
    data =new ItemModel(Q_NULLPTR);
    data->setHeaderTitle(title);
    data->BindingData(values);
    selections = new QItemSelectionModel(data);

    table = new QTableView;
    table->setModel(data);
    table->setSelectionModel(selections);
    table->setItemDelegate(new MyTableViewStyleDelegate());
    table->horizontalHeader()->setSectionsMovable(true);
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->verticalHeader()->setSectionsMovable(true);
    table->horizontalHeader()->setStretchLastSection(true);
    // Set StaticContents to enable minimal repaints on resizes.
    table->viewport()->setAttribute(Qt::WA_StaticContents);
    table->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(table, SIGNAL(customContextMenuRequested(QPoint)),SLOT(customMenuRequested(QPoint)));

    //table->setStyleSheet("QTableView{background-color: rgb(250, 250, 115);" "alternate-background-color: rgb(141, 163, 215);}");
    //table->setItemDelegateForColumn(0,new MyLineItemDelegate());
    table->setItemDelegateForColumn(0,new CheckBoxDelegate(table));

    table->setItemDelegateForColumn(1,new ReadOnlyDelegate());
    table->setSelectionBehavior(QAbstractItemView::SelectRows);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->setIconSize(QSize(1,1));
    //header checkbox
    TableCheckedHeader *m_customHeader = NULL;
    m_customHeader = new TableCheckedHeader(Qt::Horizontal, this);
    table->setHorizontalHeader(m_customHeader);
    connect(m_customHeader, SIGNAL(toggled(bool)), this, SLOT(_headertoggled(bool)));
    page->addWidget(table);


    QTreeView *tree = new QTreeView;
    tree->setModel(data);
    tree->setSelectionModel(selections);

    tree->setUniformRowHeights(true);
    tree->header()->setStretchLastSection(false);
    tree->viewport()->setAttribute(Qt::WA_StaticContents);
    // Disable the focus rect to get minimal repaints when scrolling on Mac.
    tree->setAttribute(Qt::WA_MacShowFocusRect, false);
    page->addWidget(tree);

    list = new QListView;
    //QObject::connect(list,SIGNAL(doubleClicked(QModelIndex),this,SLOT(doubleClicked(QModelIndex))));
    list->setModel(data);
    list->setIconSize(QSize(80,80));

    list->setItemDelegate(new MyListItemDelegege());
    list->setSelectionModel(selections);
    list->setSpacing(5);
    list->setViewMode(QListView::IconMode);
    list->setDragEnabled(false);
    list->setSelectionRectVisible(false);
    //list->setSelectionMode(QAbstractItemView::ExtendedSelection);
    list->setAlternatingRowColors(false);
    list->setResizeMode(QListWidget::Adjust);
    //list->viewport()->setAttribute(Qt::WA_StaticContents);

    list->setAttribute(Qt::WA_MacShowFocusRect, true);
    //list->setItemDelegateForColumn(1,new MyLineItemDelegate());

    list->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //menu
    list->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(list,SIGNAL(customContextMenuRequested(QPoint)),SLOT(CustomListMenuRequested(QPoint)));
    page->addWidget(list);




    this->setCentralWidget(page);
}
Example #4
0
// -------------------------------------------------------------------------
void ctkTreeComboBox::resizePopup()
{
  // copied from QComboBox.cpp
  Q_D(ctkTreeComboBox);

  QStyle * const style = this->style();
  QWidget* container = qobject_cast<QWidget*>(this->view()->parent());

  QStyleOptionComboBox opt;
  this->initStyleOption(&opt);
  QRect listRect(style->subControlRect(QStyle::CC_ComboBox, &opt,
                                       QStyle::SC_ComboBoxListBoxPopup, this));
  QRect screen = QApplication::desktop()->availableGeometry(
    QApplication::desktop()->screenNumber(this));
  QPoint below = this->mapToGlobal(listRect.bottomLeft());
  int belowHeight = screen.bottom() - below.y();
  QPoint above = this->mapToGlobal(listRect.topLeft());
  int aboveHeight = above.y() - screen.y();
  bool boundToScreen = !this->window()->testAttribute(Qt::WA_DontShowOnScreen);

  const bool usePopup = style->styleHint(QStyle::SH_ComboBox_Popup, &opt, this);
    {
    int listHeight = 0;
    int count = 0;
    QStack<QModelIndex> toCheck;
    toCheck.push(this->view()->rootIndex());
#ifndef QT_NO_TREEVIEW
    QTreeView *treeView = qobject_cast<QTreeView*>(this->view());
    if (treeView && treeView->header() && !treeView->header()->isHidden())
      listHeight += treeView->header()->height();
#endif
    while (!toCheck.isEmpty())
      {
      QModelIndex parent = toCheck.pop();
      for (int i = 0; i < this->model()->rowCount(parent); ++i)
        {
        QModelIndex idx = this->model()->index(i, this->modelColumn(), parent);
        if (!idx.isValid())
          {
          continue;
          }
        listHeight += this->view()->visualRect(idx).height(); /* + container->spacing() */;
#ifndef QT_NO_TREEVIEW
        if (this->model()->hasChildren(idx) && treeView && treeView->isExpanded(idx))
          {
          toCheck.push(idx);
          }
#endif
        ++count;
        if (!usePopup && count > this->maxVisibleItems())
          {
          toCheck.clear();
          break;
          }
        }
      }
    listRect.setHeight(listHeight);
    }
      {
      // add the spacing for the grid on the top and the bottom;
      int heightMargin = 0;//2*container->spacing();

      // add the frame of the container
      int marginTop, marginBottom;
      container->getContentsMargins(0, &marginTop, 0, &marginBottom);
      heightMargin += marginTop + marginBottom;

      //add the frame of the view
      this->view()->getContentsMargins(0, &marginTop, 0, &marginBottom);
      //marginTop += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->top;
      //marginBottom += static_cast<QAbstractScrollAreaPrivate *>(QObjectPrivate::get(this->view()))->bottom;
      heightMargin += marginTop + marginBottom;

      listRect.setHeight(listRect.height() + heightMargin);
      }

      // Add space for margin at top and bottom if the style wants it.
      if (usePopup)
        {
        listRect.setHeight(listRect.height() + style->pixelMetric(QStyle::PM_MenuVMargin, &opt, this) * 2);
        }

      // Make sure the popup is wide enough to display its contents.
      if (usePopup)
        {
        const int diff = d->computeWidthHint() - this->width();
        if (diff > 0)
          {
          listRect.setWidth(listRect.width() + diff);
          }
        }

      //we need to activate the layout to make sure the min/maximum size are set when the widget was not yet show
      container->layout()->activate();
      //takes account of the minimum/maximum size of the container
      listRect.setSize( listRect.size().expandedTo(container->minimumSize())
                        .boundedTo(container->maximumSize()));

      // make sure the widget fits on screen
      if (boundToScreen)
        {
        if (listRect.width() > screen.width() )
          {
          listRect.setWidth(screen.width());
          }
        if (this->mapToGlobal(listRect.bottomRight()).x() > screen.right())
          {
          below.setX(screen.x() + screen.width() - listRect.width());
          above.setX(screen.x() + screen.width() - listRect.width());
          }
        if (this->mapToGlobal(listRect.topLeft()).x() < screen.x() )
          {
          below.setX(screen.x());
          above.setX(screen.x());
          }
        }

      if (usePopup)
        {
        // Position horizontally.
        listRect.moveLeft(above.x());

#ifndef Q_WS_S60
        // Position vertically so the curently selected item lines up
        // with the combo box.
        const QRect currentItemRect = this->view()->visualRect(this->view()->currentIndex());
        const int offset = listRect.top() - currentItemRect.top();
        listRect.moveTop(above.y() + offset - listRect.top());
#endif

      // Clamp the listRect height and vertical position so we don't expand outside the
      // available screen geometry.This may override the vertical position, but it is more
      // important to show as much as possible of the popup.
        const int height = !boundToScreen ? listRect.height() : qMin(listRect.height(), screen.height());
#ifdef Q_WS_S60
        //popup needs to be stretched with screen minimum dimension
        listRect.setHeight(qMin(screen.height(), screen.width()));
#else
        listRect.setHeight(height);
#endif

        if (boundToScreen)
          {
          if (listRect.top() < screen.top())
            {
            listRect.moveTop(screen.top());
            }
          if (listRect.bottom() > screen.bottom())
            {
            listRect.moveBottom(screen.bottom());
            }
          }
#ifdef Q_WS_S60
        if (screen.width() < screen.height())
          {
          // in portait, menu should be positioned above softkeys
          listRect.moveBottom(screen.bottom());
          }
        else
          {
          TRect staConTopRect = TRect();
          AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EStaconTop, staConTopRect);
          listRect.setWidth(listRect.height());
          //by default popup is centered on screen in landscape
          listRect.moveCenter(screen.center());
          if (staConTopRect.IsEmpty())
            {
            // landscape without stacon, menu should be at the right
            (opt.direction == Qt::LeftToRight) ? listRect.setRight(screen.right()) :
              listRect.setLeft(screen.left());
            }
          }
#endif
        }
      else if (!boundToScreen || listRect.height() <= belowHeight)
        {
        listRect.moveTopLeft(below);
        }
      else if (listRect.height() <= aboveHeight)
        {
        listRect.moveBottomLeft(above);
        }
      else if (belowHeight >= aboveHeight)
        {
        listRect.setHeight(belowHeight);
        listRect.moveTopLeft(below);
        }
      else
        {
        listRect.setHeight(aboveHeight);
        listRect.moveBottomLeft(above);
        }

#if QT_VERSION < QT_VERSION_CHECK(5,0,0) && !defined QT_NO_IM
      if (QInputContext *qic = this->inputContext())
        {
        qic->reset();
        }
#endif
      QScrollBar *sb = this->view()->horizontalScrollBar();
      Qt::ScrollBarPolicy policy = this->view()->horizontalScrollBarPolicy();
      bool needHorizontalScrollBar =
        (policy == Qt::ScrollBarAsNeeded || policy == Qt::ScrollBarAlwaysOn)
        && sb->minimum() < sb->maximum();
      if (needHorizontalScrollBar)
        {
        listRect.adjust(0, 0, 0, sb->height());
        }
      container->setGeometry(listRect);
}
Example #5
0
int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
	QWidget * main_wg = new QWidget;

	// cria um objeto "splitter" para compartilhar widgets:    
	QSplitter *splitter = new QSplitter(main_wg);

	// cria um "model" usando o "StandardModel"
	QStandardItemModel *model = new QStandardItemModel;

	const int totCols = 3;
	int col;
	// define os títulos das colunas:
	for (col = 0; col < totCols; ++col) 
	{
		model->setHorizontalHeaderItem(col, 
			new QStandardItem( QString("COL-%1").arg(col+1) ) );
	}
	
	// alimenta linhas, colunas e sub-níveis:	
	QStandardItem *parentItem = model->invisibleRootItem();
	
	const int iniLevel = 0;
	const int totLevels= 3;
	QString prevRows("");
	QVector<QSize> vec_ColsRows; // colunas, linhas de cada nível 
	vec_ColsRows.reserve( totLevels );	
				// quantidade-colunas, quantidade-linhas
	vec_ColsRows << QSize(3,10) << QSize(3,3) << QSize(3,2) ;
	populate_model ( parentItem, vec_ColsRows,
						 iniLevel, prevRows);
	
	// Neste exemplo,
	// O "model" foi alimentado com linhas, colunas e sub-níveis:
	// E serão criadas 4 "views" (uma "tree", uma "table", uma "list" e uma "comboBox")
	// relacionadas ao mesmo "model";
	// Cada "view" exibe os dados de uma determinada maneira;

	// 1- ==== a primeira "view" é uma "tree":
	QTreeView *tree = new QTreeView(splitter);
	tree->setModel(model);
	// habilita classificação na tree:
	tree->setSortingEnabled(true);
	// classifica
	tree->sortByColumn(0);	
	// expande toda a árvore:
	tree->expandAll();
	// força largura de todas as colunas
	// para exibição completa do texto dos seus itens
	for (col = 0; col < totCols; ++col)
		tree->resizeColumnToContents(col);

	// configura o header para permitir mudança na ordem de classificacão:
	QHeaderView * hdrTree = tree->header();
	hdrTree->setClickable (true);
	hdrTree->setSortIndicator(0,Qt::AscendingOrder);
	hdrTree->setSortIndicatorShown(true);
	hdrTree->setMovable(true); // permite mover colunas do header

	// 2- ==== a segunda "view" é uma "table"
	QTableView *table = new QTableView(splitter);
	table->setModel(model);
	table->setAlternatingRowColors(true);
	// habilita classificação na table:
	table->setSortingEnabled(true);
	// classifica
	table->sortByColumn(0);	

	// configura o header para permitir mudança na ordem de classificacão:
	QHeaderView * hdrTable = table->horizontalHeader();
	hdrTable->setClickable (true);
	hdrTable->setSortIndicator(0,Qt::AscendingOrder);
	hdrTable->setSortIndicatorShown(true);
	hdrTable->setMovable(true); // permite mover colunas do header
			
	// 3- ==== a terceira view é uma "list": 
	QListView *list = new QListView(splitter);
	list->setModel(model);

	// 4- ==== a quarta "view" é uma "comboBox"
	QComboBox *combo = new QComboBox;
	combo->setModel(model);

	// configura a "splitter" definindo a largura de cada "view"
	int width = 800;	
	QList< int > cols;
	cols << int(width* 0.45) << int(width*0.45) << int(width*0.1);
	splitter->setSizes(cols);	

	// layout para agrupar a "combo" e a "splitter":
	QGridLayout * glayMain = new QGridLayout;
	main_wg->setLayout( glayMain);
	glayMain->addWidget( combo, 0, 1); // linha 0, coluna 0;
	glayMain->setRowMinimumHeight(1, glayMain->verticalSpacing() * 4); // linha 1: linha de separação
	glayMain->addWidget( splitter, 2, 0, 1, 3 ); // linha 2, coluna 0, rowSpan 1, colSpan 3

	main_wg->setWindowTitle("06_standard - 4 'views' usando o mesmo 'model' (StandardModel) - recursivo");
	main_wg->resize(800,500);	

	main_wg->show();
	return app.exec();
}
Example #6
0
int TreeView::header(lua_State * L) // const : QHeaderView * 
{
    QTreeView* obj = QtObject<QTreeView>::check( L, 1);
    QtObject<QHeaderView>::create( L, obj->header() );
	return 1;
}
void qjackctlInterfaceComboBox::populateModel (void)
{
	const bool bBlockSignals = QComboBox::blockSignals(true);

	QComboBox::setUpdatesEnabled(false);
	QComboBox::setDuplicatesEnabled(false);

	QLineEdit *pLineEdit = QComboBox::lineEdit();

	// FIXME: Only valid for ALSA, Sun and OSS devices,
	// for the time being... and also CoreAudio ones too.
	const QString& sDriver = m_pDriverComboBox->currentText();
	const bool bAlsa      = (sDriver == "alsa");
	const bool bSun       = (sDriver == "sun");
	const bool bOss       = (sDriver == "oss");
#ifdef CONFIG_COREAUDIO
	const bool bCoreaudio = (sDriver == "coreaudio");
	std::map<QString, AudioDeviceID> coreaudioIdMap;
#endif
#ifdef CONFIG_PORTAUDIO
	const bool bPortaudio = (sDriver == "portaudio");
#endif
	QString sCurName = pLineEdit->text();
	QString sName, sSubName;
	
	int iCards = 0;

	clearCards();

	int iCurCard = -1;

	if (bAlsa) {
#ifdef CONFIG_ALSA_SEQ
		// Enumerate the ALSA cards and PCM harfware devices...
		snd_ctl_t *handle;
		snd_ctl_card_info_t *info;
		snd_pcm_info_t *pcminfo;
		snd_ctl_card_info_alloca(&info);
		snd_pcm_info_alloca(&pcminfo);
		const QString sPrefix("hw:%1");
		const QString sSuffix(" (%1)");
		const QString sSubSuffix("%1,%2");
		QString sName2, sSubName2;
		bool bCapture, bPlayback;
		int iCard = -1;
		while (snd_card_next(&iCard) >= 0 && iCard >= 0) {
			sName = sPrefix.arg(iCard);
			if (snd_ctl_open(&handle, sName.toUtf8().constData(), 0) >= 0
				&& snd_ctl_card_info(handle, info) >= 0) {
				sName2 = sPrefix.arg(snd_ctl_card_info_get_id(info));
				addCard(sName2, snd_ctl_card_info_get_name(info) + sSuffix.arg(sName));
				if (sCurName == sName || sCurName == sName2)
					iCurCard = iCards;
				++iCards;
				int iDevice = -1;
				while (snd_ctl_pcm_next_device(handle, &iDevice) >= 0
					&& iDevice >= 0) {
					// Capture devices..
					bCapture = false;
					if (m_iAudio == QJACKCTL_CAPTURE ||
						m_iAudio == QJACKCTL_DUPLEX) {
						snd_pcm_info_set_device(pcminfo, iDevice);
						snd_pcm_info_set_subdevice(pcminfo, 0);
						snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_CAPTURE);
						bCapture = (snd_ctl_pcm_info(handle, pcminfo) >= 0);
					}
					// Playback devices..
					bPlayback = false;
					if (m_iAudio == QJACKCTL_PLAYBACK ||
						m_iAudio == QJACKCTL_DUPLEX) {
						snd_pcm_info_set_device(pcminfo, iDevice);
						snd_pcm_info_set_subdevice(pcminfo, 0);
						snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_PLAYBACK);
						bPlayback = (snd_ctl_pcm_info(handle, pcminfo) >= 0);
					}
					// List iif compliant with the audio mode criteria...
					if ((m_iAudio == QJACKCTL_CAPTURE && bCapture && !bPlayback) ||
						(m_iAudio == QJACKCTL_PLAYBACK && !bCapture && bPlayback) ||
						(m_iAudio == QJACKCTL_DUPLEX && bCapture && bPlayback)) {
						sSubName  = sSubSuffix.arg(sName).arg(iDevice);
						sSubName2 = sSubSuffix.arg(sName2).arg(iDevice);
						addCard(sSubName2, snd_pcm_info_get_name(pcminfo) + sSuffix.arg(sSubName));
						if (sCurName == sSubName || sCurName == sSubName2)
							iCurCard = iCards;
						++iCards;
					}
				}
				snd_ctl_close(handle);
			}
		}
#endif 	// CONFIG_ALSA_SEQ
	}
	else
	if (bSun) {
		QFile file("/var/run/dmesg.boot");
		if (file.open(QIODevice::ReadOnly)) {
			QTextStream stream(&file);
			QString sLine;
			QRegExp rxDevice("audio([0-9]) at (.*)");
			while (!stream.atEnd()) {
				sLine = stream.readLine();
				if (rxDevice.exactMatch(sLine)) {
					sName = "/dev/audio" + rxDevice.cap(1);
					addCard(sName, rxDevice.cap(2));
					if (sCurName == sName)
						iCurCard = iCards;
					++iCards;
				}
			}
			file.close();
		}
	}
	else
	if (bOss) {
		// Enumerate the OSS Audio devices...
		QFile file("/dev/sndstat");
		if (file.open(QIODevice::ReadOnly)) {
			QTextStream stream(&file);
			QString sLine;
			bool bAudioDevices = false;
			QRegExp rxHeader("Audio devices.*", Qt::CaseInsensitive);
			QRegExp rxDevice("([0-9]+):[ ]+(.*)");
			while (!stream.atEnd()) {
				sLine = stream.readLine();
				if (bAudioDevices) {
					if (rxDevice.exactMatch(sLine)) {
						sName = "/dev/dsp" + rxDevice.cap(1);
						addCard(sName, rxDevice.cap(2));
						if (sCurName == sName)
							iCurCard = iCards;
						++iCards;
					}
					else break;
				}
				else if (rxHeader.exactMatch(sLine))
					bAudioDevices = true;
			}
			file.close();
		}
	}
#ifdef CONFIG_COREAUDIO
	else if (bCoreaudio) {
		// Find out how many Core Audio devices are there, if any...
		// (code snippet gently "borrowed" from Stephane Letz jackdmp;)
		OSStatus err;
		Boolean isWritable;
		UInt32 outSize = sizeof(isWritable);
		err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices,
				&outSize, &isWritable);
		if (err == noErr) {
			// Calculate the number of device available...
			int numCoreDevices = outSize / sizeof(AudioDeviceID);
			// Make space for the devices we are about to get...
			AudioDeviceID *coreDeviceIDs = new AudioDeviceID [numCoreDevices];
			err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices,
					&outSize, (void *) coreDeviceIDs);
			if (err == noErr) {
				// Look for the CoreAudio device name...
				char coreDeviceName[256];
				UInt32 nameSize = 256;
				for (int i = 0; i < numCoreDevices; i++) {
					err = AudioDeviceGetPropertyInfo(coreDeviceIDs[i],
							0, true, kAudioDevicePropertyDeviceName,
							&outSize, &isWritable);
					if (err == noErr) {
						err = AudioDeviceGetProperty(coreDeviceIDs[i],
								0, true, kAudioDevicePropertyDeviceName,
								&nameSize, (void *) coreDeviceName);
						if (err == noErr) {
							char drivername[128];
							UInt32 dnsize = 128;
							// this returns the unique id for the device
							// that must be used on the commandline for jack
							if (getDeviceUIDFromID(coreDeviceIDs[i],
								drivername, dnsize) == noErr) {
								sName = drivername;
							} else {
								sName = "Error";
							}
							coreaudioIdMap[sName] = coreDeviceIDs[i];
							// TODO: hide this ugly ID from the user,
							// only show human readable name
							// humanreadable \t UID
							sSubName = QString(coreDeviceName);
							addCard(sSubName, sName);
							if (sCurName == sName || sCurName == sSubName)
								iCurCard = iCards;
							++iCards;
						}
					}
				}
			}
			delete [] coreDeviceIDs;
		}
	}
#endif 	// CONFIG_COREAUDIO
#ifdef CONFIG_PORTAUDIO
	else if (bPortaudio) {
		const QStringList& names = PortAudioProber::getNames(this);
		const int iCards = names.size();
		for (int i = 0; i < iCards; ++i) {
			const QString& sName = names[i];
			if (sCurName == sName)
				iCurCard = iCards;
			addCard(sName, QString());
		}
	}
#endif  // CONFIG_PORTAUDIO

	addCard(m_sDefName, QString());
	if (sCurName == m_sDefName || sCurName.isEmpty())
		iCurCard = iCards;
	++iCards;

	QTreeView *pTreeView = static_cast<QTreeView *> (QComboBox::view());
#if QT_VERSION < 0x050000
	pTreeView->header()->setResizeMode(QHeaderView::ResizeToContents);
#else
	pTreeView->header()->resizeSections(QHeaderView::ResizeToContents);
#endif
	pTreeView->setMinimumWidth(
		pTreeView->sizeHint().width() + QComboBox::iconSize().width());

	QComboBox::setCurrentIndex(iCurCard);

	pLineEdit->setText(sCurName);

	QComboBox::setUpdatesEnabled(true);
	QComboBox::blockSignals(bBlockSignals);
}
Example #8
0
DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *parent)
	: QDialog(parent), predefinedTokens(_predefinedTokens)
{
	nameLabel = new QLabel(tr("&Name:"));
	nameEdit = new QLineEdit(tr("Token"));
	nameEdit->selectAll();
	nameLabel->setBuddy(nameEdit);

	colorLabel = new QLabel(tr("C&olor:"));
	colorEdit = new QComboBox;
	colorEdit->addItem(tr("white"), "w");
	colorEdit->addItem(tr("blue"), "u");
	colorEdit->addItem(tr("black"), "b");
	colorEdit->addItem(tr("red"), "r");
	colorEdit->addItem(tr("green"), "g");
	colorEdit->addItem(tr("multicolor"), "m");
	colorEdit->addItem(tr("colorless"), QString());
	colorLabel->setBuddy(colorEdit);

	ptLabel = new QLabel(tr("&P/T:"));
	ptEdit = new QLineEdit;
	ptLabel->setBuddy(ptEdit);

	annotationLabel = new QLabel(tr("&Annotation:"));
	annotationEdit = new QLineEdit;
	annotationLabel->setBuddy(annotationEdit);
	
	destroyCheckBox = new QCheckBox(tr("&Destroy token when it leaves the table"));
	destroyCheckBox->setChecked(true);

	QGridLayout *grid = new QGridLayout;
	grid->addWidget(nameLabel, 0, 0);
	grid->addWidget(nameEdit, 0, 1);
	grid->addWidget(colorLabel, 1, 0);
	grid->addWidget(colorEdit, 1, 1);
	grid->addWidget(ptLabel, 2, 0);
	grid->addWidget(ptEdit, 2, 1);
	grid->addWidget(annotationLabel, 3, 0);
	grid->addWidget(annotationEdit, 3, 1);
	grid->addWidget(destroyCheckBox, 4, 0, 1, 2);
	
	QGroupBox *tokenDataGroupBox = new QGroupBox(tr("Token data"));
	tokenDataGroupBox->setLayout(grid);
	
	cardDatabaseModel = new CardDatabaseModel(db, this);
	cardDatabaseDisplayModel = new CardDatabaseDisplayModel(this);
	cardDatabaseDisplayModel->setSourceModel(cardDatabaseModel);
	cardDatabaseDisplayModel->setIsToken(CardDatabaseDisplayModel::ShowTrue);
	
	chooseTokenFromAllRadioButton = new QRadioButton(tr("Show &all tokens"));
	connect(chooseTokenFromAllRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromAll(bool)));
	chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck"));
	connect(chooseTokenFromDeckRadioButton, SIGNAL(toggled(bool)), this, SLOT(actChooseTokenFromDeck(bool)));
	QTreeView *chooseTokenView = new QTreeView;
	chooseTokenView->setModel(cardDatabaseDisplayModel);
	chooseTokenView->setUniformRowHeights(true);
	chooseTokenView->setRootIsDecorated(false);
	chooseTokenView->setAlternatingRowColors(true);
	chooseTokenView->setSortingEnabled(true);
	chooseTokenView->sortByColumn(0, Qt::AscendingOrder);
	chooseTokenView->resizeColumnToContents(0);
	chooseTokenView->header()->setStretchLastSection(false);
	chooseTokenView->header()->hideSection(1);
	chooseTokenView->header()->hideSection(2);
	chooseTokenView->header()->setResizeMode(3, QHeaderView::ResizeToContents);
	chooseTokenView->header()->setResizeMode(4, QHeaderView::ResizeToContents);
	connect(chooseTokenView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(tokenSelectionChanged(QModelIndex, QModelIndex)));
	
	if (predefinedTokens.isEmpty())
		chooseTokenFromAllRadioButton->setChecked(true);
	else {
		chooseTokenFromDeckRadioButton->setChecked(true);
		cardDatabaseDisplayModel->setCardNameSet(QSet<QString>::fromList(predefinedTokens));
	}
	
	QVBoxLayout *tokenChooseLayout = new QVBoxLayout;
	tokenChooseLayout->addWidget(chooseTokenFromAllRadioButton);
	tokenChooseLayout->addWidget(chooseTokenFromDeckRadioButton);
	tokenChooseLayout->addWidget(chooseTokenView);
	
	QGroupBox *tokenChooseGroupBox = new QGroupBox(tr("Choose token from list"));
	tokenChooseGroupBox->setLayout(tokenChooseLayout);
	
	QVBoxLayout *leftVBox = new QVBoxLayout;
	leftVBox->addWidget(tokenDataGroupBox);
	leftVBox->addStretch();
	
	QHBoxLayout *hbox = new QHBoxLayout;
	hbox->addLayout(leftVBox);
	hbox->addWidget(tokenChooseGroupBox);
	
	QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
	connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
	
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addLayout(hbox);
	mainLayout->addWidget(buttonBox);
	setLayout(mainLayout);

	setWindowTitle(tr("Create token"));
	setFixedHeight(sizeHint().height());
	setMinimumWidth(300);
}