MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); dal_main = new DAL_main(this); QCoreApplication::setApplicationName("pocskaf2"); QCoreApplication::setOrganizationName("team2"); QSettings prevSettings("team2", "pocskaf2"); if (prevSettings.value("databaseName").isNull() || prevSettings.value("port").isNull() || prevSettings.value("username").isNull() || prevSettings.value("password").isNull() || prevSettings.value("host").isNull()) { accessdb *access = new accessdb(this); access->marker = 1; access->exec(); } else { if( dal_main->setConnection(prevSettings.value("databaseName").toString(),prevSettings.value("port").toInt(),prevSettings.value("host").toString(),prevSettings.value("username").toString(),prevSettings.value("password").toString())) { QMessageBox::information(this, tr("Соединение успешно"), tr("Соединение с базой данных установлено")); } else { QMessageBox::critical(this, tr("Ошибка подключения"), tr("Соединение с базой данных невозможно")); accessdb *access = new accessdb(this); access->marker = 1; access->exec(); } } Authorization *w=new Authorization(this) ; w->setWindowFlags(Qt::Dialog | Qt::Desktop); w->exec(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(showTime())); timer->start(1000); showTime(); QPixmap pixmap(":/img/img/pocs2.png"); QSplashScreen *splash = new QSplashScreen(pixmap); QFont splashFont; splashFont.setPixelSize(17); splash->setFont(splashFont); splash->show(); QTime time; time.start(); for (int i = 0; i < 100; ) { if (time.elapsed() > 5) { time.start(); ++i; } splash->showMessage(tr(" Загрузка системы: ") + QString::number(i) + "%", Qt::AlignLeft | Qt::AlignBottom , Qt::black); QCoreApplication::processEvents(); } QSqlQuery * empNameQuery = new QSqlQuery(dal_main->db); empNameQuery->prepare("SELECT st_fio, st_photo FROM is_sotrudniki where id_sotr = " + QString::number(dal_main->getCurrentEmployee())); empNameQuery->exec(); empNameQuery->first(); if(empNameQuery->isValid()) this->setWindowTitle("SMT v. 1.0 (текущий пользователь - " + empNameQuery->value(0).toString() + ")"); checkNaznPoruch = new QSqlQuery(dal_main->db); checkNaznPoruch->prepare("SELECT count(id_poruchenie) FROM is_porucheniya where checkPoruch = 0 and poruchitel = " + QString::number(dal_main->getCurrentEmployee())); checkIspolPoruch = new QSqlQuery(dal_main->db); checkIspolPoruch->prepare("SELECT count(id_poruchenie) FROM is_porucheniya where checkIspoln = 0 and ispolnitel = " + QString::number(dal_main->getCurrentEmployee())); checker = new QTimer; // checkDatePoruch = new QSqlQuery(dal_main->db); // checkDatePoruch->prepare("SELECT count(id_poruchenie) FROM is_porucheniya where check_date and checkIspoln = 1 and ispolnitel = " + QString::number(dal_main->getCurrentEmployee())); connect(checker,SIGNAL(timeout()),this,SLOT(on_check())); checker->setInterval(10000); checker->start(); icon = new QSystemTrayIcon(this); icon->setIcon(QIcon(":/img/img/institution_icon.png")); icon->show(); //icon->setContextMenu(ui->menu_file); connect(icon,SIGNAL(messageClicked()),this,SLOT(on_actionChecks())); //Open form Request ui->pushButton_show->setVisible(false); ui->pushButton_show->setFlat(true); ui->pushButton_hide->setFlat(true); ui->groupBox_main->setContentsMargins(0,0,0,0); ui->mdiArea->setVisible(false); QGraphicsDropShadowEffect * ef1 = new QGraphicsDropShadowEffect; ef1->setBlurRadius(15); QGraphicsDropShadowEffect * ef2 = new QGraphicsDropShadowEffect; ef2->setBlurRadius(15); QGraphicsDropShadowEffect * ef3 = new QGraphicsDropShadowEffect; ef3->setBlurRadius(15); QGraphicsDropShadowEffect * ef4 = new QGraphicsDropShadowEffect; ef4->setBlurRadius(15); QGraphicsDropShadowEffect * ef5 = new QGraphicsDropShadowEffect; ef5->setBlurRadius(15); QGraphicsDropShadowEffect * ef6 = new QGraphicsDropShadowEffect; ef6->setBlurRadius(15); QGraphicsDropShadowEffect * ef7 = new QGraphicsDropShadowEffect; ef7->setBlurRadius(15); QGraphicsDropShadowEffect * ef8 = new QGraphicsDropShadowEffect; ef8->setBlurRadius(15); QGraphicsDropShadowEffect * ef9 = new QGraphicsDropShadowEffect; ef9->setBlurRadius(15); ui->pushButton1->setGraphicsEffect(ef1); ui->pushButton2->setGraphicsEffect(ef2); ui->pushButton3->setGraphicsEffect(ef3); ui->pushButton4->setGraphicsEffect(ef4); ui->pushButton5->setGraphicsEffect(ef5); ui->pushButton6->setGraphicsEffect(ef6); ui->pushButton7->setGraphicsEffect(ef7); ui->pushButton8->setGraphicsEffect(ef8); ui->pushButton9->setGraphicsEffect(ef9); // this->setCentralWidget(ui->mdiArea); // Настраиваем виджет перекрытия QLightBoxWidget* lightBox = new QLightBoxWidget(this); QLabel* lbTitle = new QLabel(empNameQuery->value(0).toString()); lbTitle->setStyleSheet("font-size: 28px; font-weight: bold; color: white"); QLabel* lbProgress = new QLabel; QMovie* progressMovie = new QMovie(empNameQuery->value(1).toString()); progressMovie->setScaledSize(QSize(250,200)); lbProgress->setMovie(progressMovie); progressMovie->start(); QLabel* lbDescription = new QLabel(tr("Для входа в систему нажмите Войти")); lbDescription->setStyleSheet("color: white"); QPushButton* lbClose = new QPushButton(tr("Войти")); QGridLayout* lbLayout = new QGridLayout; lbLayout->setRowStretch(0, 1); lbLayout->setColumnStretch(0, 1); lbLayout->addWidget(lbTitle, 1, 1); lbLayout->addWidget(lbProgress, 1, 2, Qt::AlignRight); lbLayout->setColumnStretch(3, 1); lbLayout->addWidget(lbDescription, 2, 1, 1, 2); lbLayout->addWidget(lbClose, 3, 2); lbLayout->setRowStretch(4, 1); connect(ui->action_Oteshel, SIGNAL(triggered()), lightBox, SLOT(show())); connect(lbClose, SIGNAL(clicked()), lightBox, SLOT(hide())); lightBox->setLayout(lbLayout); // ui->menuBar->setVisible(false); ui->mainToolBar->setVisible(false); ui->groupBox->setVisible(false); splash->finish(this); /*QGridLayout *userl = new QGridLayout(ui->userWidget); ui->userWidget->setLayout(userl); QLabel* lbProgress1 = new QLabel; QMovie* progressMovie1 = new QMovie(empNameQuery->value(1).toString()); progressMovie1->setScaledSize(QSize(250,200)); lbProgress1->setMovie(progressMovie1); progressMovie1->start(); userl->addWidget(lbProgress1);*/ }
QImage QRImageWidget::exportImage() { if(!pixmap()) return QImage(); return pixmap()->toImage().scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE); }
void QRImageWidget::contextMenuEvent(QContextMenuEvent *event) { if(!pixmap()) return; contextMenu->exec(event->globalPos()); }
void QPixmapIconEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) { painter->drawPixmap(rect, pixmap(rect.size(), mode, state)); }
int main(int argc, char **argv) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setOption(QSurfaceFormat::StereoBuffers, true); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext, true); #endif QSurfaceFormat::setDefaultFormat(format); } //The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application //DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows) QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); //QT initialiation qccApplication app(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif //splash screen QSplashScreen* splash = 0; QTime splashStartTime; //restore some global parameters { QSettings settings; settings.beginGroup(ccPS::GlobalShift()); double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble(); double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble(); settings.endGroup(); ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0)); ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord); ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag); } //Command line mode? bool commandLine = (argc > 1 && argv[1][0] == '-'); //specific case: translation file selection int lastArgumentIndex = 1; QTranslator translator; if (commandLine && QString(argv[1]).toUpper() == "-LANG") { QString langFilename = QString(argv[2]); //Load translation file if (translator.load(langFilename, QCoreApplication::applicationDirPath())) { qApp->installTranslator(&translator); } else { QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename)); } commandLine = false; lastArgumentIndex = 3; } //command line mode if (!commandLine) { if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //splash screen splashStartTime.start(); QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png")); splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint); splash->show(); QApplication::processEvents(); } //global structures initialization ccTimer::Init(); FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization int result = 0; if (commandLine) { //command line processing (no GUI) result = ccCommandLineParser::Parse(argc, argv); } else { //main window init. MainWindow* mainWindow = MainWindow::TheInstance(); if (!mainWindow) { QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!"); return EXIT_FAILURE; } mainWindow->show(); QApplication::processEvents(); //show current Global Shift parameters in Console { ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2") .arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0) .arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0)); } if (argc > lastArgumentIndex) { if (splash) splash->close(); //any additional argument is assumed to be a filename --> we try to load it/them QStringList filenames; for (int i = lastArgumentIndex; i<argc; ++i) filenames << QString(argv[i]); mainWindow->addToDB(filenames); } if (splash) { //we want the splash screen to be visible a minimum amount of time (1000 ms.) while (splashStartTime.elapsed() < 1000) { splash->raise(); QApplication::processEvents(); //to let the system breath! } splash->close(); QApplication::processEvents(); delete splash; splash = 0; } //let's rock! try { result = app.exec(); } catch(...) { QMessageBox::warning(0, "CC crashed!","Hum, it seems that CC has crashed... Sorry about that :)"); } } //release global structures MainWindow::DestroyInstance(); FileIOFilter::UnregisterAll(); #ifdef CC_TRACK_ALIVE_SHARED_OBJECTS //for debug purposes unsigned alive = CCShareable::GetAliveCount(); if (alive > 1) { printf("Error: some shared objects (%u) have not been released on program end!",alive); system("PAUSE"); } #endif return result; }
void AboutDialog::setLogo(const QString filename) { QPixmap pixmap(filename); label_Logo->setPixmap(pixmap); }
listMemberDialog::listMemberDialog(QWidget *parent,QString classId) { conn = database::connectByC(); QVBoxLayout *topLeftLayout = new QVBoxLayout; view = new QTableView(this); model = new QStandardItemModel(this); view->setModel(model); model->setHorizontalHeaderItem(0, new QStandardItem(tr("ID"))); model->setHorizontalHeaderItem(1, new QStandardItem(tr("Name"))); model->setHorizontalHeaderItem(2, new QStandardItem(tr("Birth year"))); model->setHorizontalHeaderItem(3, new QStandardItem(tr("Note"))); model->setHorizontalHeaderItem(4, new QStandardItem(tr("-"))); view->setColumnWidth(0,20); view->setColumnWidth(1,90); view->setColumnWidth(2,57); view->setColumnWidth(3,40); view->setColumnWidth(4,30); label = new QLabel("Member list"); topLeftLayout->addWidget(label); int rowCurrent = 0; MYSQL_RES *res = database::classMember_searchClassId(conn,classId); while(MYSQL_ROW classMemberRow = mysql_fetch_row(res)) { QString memberId = classMemberRow[1]; MYSQL_ROW memberRow = database::member_searchMemberId(conn,memberId); model->setItem(rowCurrent, 0, new QStandardItem(memberRow[0])); model->setItem(rowCurrent, 1, new QStandardItem(memberRow[1])); model->setItem(rowCurrent, 2, new QStandardItem(memberRow[2])); model->setItem(rowCurrent, 3, new QStandardItem(memberRow[3])); QPushButton *button = new QPushButton(""); QPixmap pixmap("Resources/Delete_icon.png"); QIcon buttonIcon(pixmap); button->setIcon(buttonIcon); QSignalMapper *signalMapper = new QSignalMapper(this); signalMapper->setMapping(button,memberId); QObject::connect(button,SIGNAL(clicked()),signalMapper,SLOT(map())); QObject::connect(signalMapper,SIGNAL(mapped(QString)),this,SLOT(deleteMemberAction(QString))); view->setIndexWidget(model->index(rowCurrent,4),button); rowCurrent++; } numOldMemberInDialog = rowCurrent; topLeftLayout->addWidget(view); QHBoxLayout *horizontalLayout = new QHBoxLayout(); QPushButton *saveButton = new QPushButton("Save"); QPixmap pixmap1("Resources/save_icon.png"); QIcon ButtonIcon1(pixmap1); saveButton->setIcon(ButtonIcon1); QSignalMapper *saveMapper = new QSignalMapper(this); saveMapper->setMapping(saveButton,classId); QObject::connect(saveButton,SIGNAL(clicked()),saveMapper,SLOT(map())); QObject::connect(saveMapper,SIGNAL(mapped(QString)),this,SLOT(saveListAction(QString))); horizontalLayout->addWidget(saveButton); QPushButton *addMemberButton = new QPushButton("Add Member"); QPixmap pixmap("Resources/add-icon.png"); QIcon ButtonIcon(pixmap); addMemberButton->setIcon(ButtonIcon); QObject::connect(addMemberButton,SIGNAL(clicked()),this,SLOT(addMemberAction())); horizontalLayout->addWidget(addMemberButton); setLayout(topLeftLayout); topLeftLayout->addLayout(horizontalLayout); setWindowTitle(tr("Member list")); setFixedHeight(sizeHint().height()); }
/** @short Reimplemented to show custom pixmap during drag&drop Qt's model-view classes don't provide any means of interfering with the QDrag's pixmap so we just rip off QAbstractItemView::startDrag and provide our own QPixmap. */ void MsgListView::startDrag(Qt::DropActions supportedActions) { // indexes for column 0, i.e. subject QModelIndexList baseIndexes; Q_FOREACH(const QModelIndex &index, selectedIndexes()) { if (!(model()->flags(index) & Qt::ItemIsDragEnabled)) continue; if (index.column() == Imap::Mailbox::MsgListModel::SUBJECT) baseIndexes << index; } if (!baseIndexes.isEmpty()) { QMimeData *data = model()->mimeData(baseIndexes); if (!data) return; // use screen width and itemDelegate()->sizeHint() to determine size of the pixmap int screenWidth = QApplication::desktop()->screenGeometry(this).width(); int maxWidth = qMax(400, screenWidth / 4); QSize size(maxWidth, 0); // Show a "+ X more items" text after so many entries const int maxItems = 20; QStyleOptionViewItem opt; opt.initFrom(this); opt.rect.setWidth(maxWidth); opt.rect.setHeight(itemDelegate()->sizeHint(opt, baseIndexes.at(0)).height()); size.setHeight(qMin(maxItems + 1, baseIndexes.size()) * opt.rect.height()); // State_Selected provides for nice background of the items opt.state |= QStyle::State_Selected; // paint list of selected items using itemDelegate() to be consistent with style QPixmap pixmap(size); pixmap.fill(Qt::transparent); QPainter p(&pixmap); for (int i = 0; i < baseIndexes.size(); ++i) { opt.rect.moveTop(i * opt.rect.height()); if (i == maxItems) { p.fillRect(opt.rect, palette().color(QPalette::Disabled, QPalette::Highlight)); p.setBrush(palette().color(QPalette::Disabled, QPalette::HighlightedText)); p.drawText(opt.rect, Qt::AlignRight, tr("+ %n additional item(s)", 0, baseIndexes.size() - maxItems)); break; } itemDelegate()->paint(&p, opt, baseIndexes.at(i)); } QDrag *drag = new QDrag(this); drag->setPixmap(pixmap); drag->setMimeData(data); drag->setHotSpot(QPoint(0, 0)); Qt::DropAction dropAction = Qt::IgnoreAction; if (defaultDropAction() != Qt::IgnoreAction && (supportedActions & defaultDropAction())) dropAction = defaultDropAction(); else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove) dropAction = Qt::CopyAction; if (drag->exec(supportedActions, dropAction) == Qt::MoveAction) { // QAbstractItemView::startDrag calls d->clearOrRemove() here, so // this is a copy of QAbstractItemModelPrivate::clearOrRemove(); const QItemSelection selection = selectionModel()->selection(); QList<QItemSelectionRange>::const_iterator it = selection.constBegin(); if (!dragDropOverwriteMode()) { for (; it != selection.constEnd(); ++it) { QModelIndex parent = it->parent(); if (it->left() != 0) continue; if (it->right() != (model()->columnCount(parent) - 1)) continue; int count = it->bottom() - it->top() + 1; model()->removeRows(it->top(), count, parent); } } else { // we can't remove the rows so reset the items (i.e. the view is like a table) QModelIndexList list = selection.indexes(); for (int i = 0; i < list.size(); ++i) { QModelIndex index = list.at(i); QMap<int, QVariant> roles = model()->itemData(index); for (QMap<int, QVariant>::Iterator it = roles.begin(); it != roles.end(); ++it) it.value() = QVariant(); model()->setItemData(index, roles); } } } } }
//------------------------------------------------------------------------- SetupDialog::SetupDialog(MainWindow *parent) : QDialog(parent), mMainWindow(parent) { setupUi(this); QObject::connect (fDefaultButton, SIGNAL(clicked()), this, SLOT(reset())); QObject::connect (fSysDistBox, SIGNAL(valueChanged(int)), this, SLOT(setup())); QObject::connect (fMaxDistBox, SIGNAL(valueChanged(int)), this, SLOT(setup())); QObject::connect (fSpringBox, SIGNAL(valueChanged(int)), this, SLOT(setup())); QObject::connect (fForceBox, SIGNAL(valueChanged(int)), this, SLOT(setup())); QObject::connect (fSysDistrMenu, SIGNAL(currentIndexChanged(int)), this, SLOT(setup())); QObject::connect (fOPFcheckBox, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fNSpacingcheckBox, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fResizePage2Music, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fColorButton, SIGNAL(clicked()) , this, SLOT(changeColor())); QObject::connect (fMapping, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fRawMapping, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fBoundingBoxes, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fPageBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fSystemBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fSystemSliceBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fStaffBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fMeasureBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fEventBB, SIGNAL(clicked()), this, SLOT(setup())); QObject::connect (fVoiceNumEdit, SIGNAL(valueChanged(int)), this, SLOT(voiceStaffSetup(int))); QObject::connect (fStaffNumEdit, SIGNAL(valueChanged(int)), this, SLOT(voiceStaffSetup(int))); QObject::connect (fShowAllStaffsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(voiceStaffSetup(int))); QObject::connect (fShowAllVoicesCheckBox, SIGNAL(stateChanged(int)), this, SLOT(voiceStaffSetup(int))); mSavedSettings = mMainWindow->getEngineSettings(); mSavedBBMap = mMainWindow->getBBMap(); mSavedShowMapping = mMainWindow->getShowMapping(); mSavedRawMapping = mMainWindow->getRawMapping(); mSavedShowBoxes = mMainWindow->getShowBoxes(); mSavedVoiceNum = mMainWindow->getVoiceNum(); mSavedStaffNum = mMainWindow->getStaffNum(); scoreColorChanged( mMainWindow->getScoreColor() ); set (mSavedSettings, mSavedBBMap, mSavedShowMapping, mSavedRawMapping, mSavedShowBoxes, mSavedVoiceNum, mSavedStaffNum); mFontColorMap[ GuidoHighlighter::VOICE_SEPARATOR_ELT ] = fVoiceSeparatorColorButton; mFontColorMap[ GuidoHighlighter::SCORE_SEPARATOR_ELT ] = fScoreSeparatorColorButton; mFontColorMap[ GuidoHighlighter::DURATION_ELT ] = fDurationsColorButton; mFontColorMap[ GuidoHighlighter::NOTE_ELT ] = fNotesColorButton; mFontColorMap[ GuidoHighlighter::TAG_PARAM_ELT ] = fTagsParametersColorButton; mFontColorMap[ GuidoHighlighter::TAG_ELT ] = fTagsColorButton; mFontColorMap[ GuidoHighlighter::COMMENT_ELT ] = fCommentsColorButton; mFontWeightMap[ GuidoHighlighter::VOICE_SEPARATOR_ELT ] = fVoiceSeparatorWeight; mFontWeightMap[ GuidoHighlighter::SCORE_SEPARATOR_ELT ] = fScoreSeparatorWeight; mFontWeightMap[ GuidoHighlighter::DURATION_ELT ] = fDurationsWeight; mFontWeightMap[ GuidoHighlighter::NOTE_ELT ] = fNotesWeight; mFontWeightMap[ GuidoHighlighter::TAG_PARAM_ELT ] = fTagsParametersWeight; mFontWeightMap[ GuidoHighlighter::TAG_ELT ] = fTagsWeight; mFontWeightMap[ GuidoHighlighter::COMMENT_ELT ] = fCommentsWeight; fTabWidget->setCurrentIndex(0); for ( int i = 0 ; i < GuidoHighlighter::SIZE ; i++ ) { // Set widgets properties with syntax-element id mFontColorMap[ i ]->setProperty( SYNTAX_ELT_ID , i ); mFontWeightMap[ i ]->setProperty( SYNTAX_ELT_ID , i ); // Set the color of the font-color button QColor c = mMainWindow->getHighlighter()->color( i ); QPixmap pixmap(30 , 30); pixmap.fill( c ); mFontColorMap[ i ]->setIcon( QIcon(pixmap) ); mFontColorMap[ i ]->setProperty( BUTTON_COLOR , c ); // Adds font-weight items in the combobox for ( int w = 0 ; w <= QFont::Black ; w++ ) { QString weightString = weightToString( w ); if ( weightString.size() ) mFontWeightMap[i]->addItem( weightString , w ); } // Set the current combobox item QFont::Weight weight = (QFont::Weight)mMainWindow->getHighlighter()->weight( i ); mFontWeightMap[i]->setCurrentIndex( mFontWeightMap[i]->findData( weight ) ); // Connect the font widgets to their methods connect( mFontColorMap[i] , SIGNAL(clicked()) , this , SLOT(fontColorButtonClicked()) ); connect( mFontWeightMap[i] , SIGNAL(currentIndexChanged(int)) , this , SLOT(fontWeightChanged(int)) ); mSavedColors[i] = c; mSavedWeights[i]= int(weight); } if (!mColorDialog) { mColorDialog = new QColorDialog( this ); mColorDialog->setWindowTitle("Choose score color"); mColorDialog->setOption (QColorDialog::NoButtons); } QSettings settings; QPoint pos = settings.value(SETUP_DIALOG_POS_SETTING, QPoint(300, 300)).toPoint(); QSize winSize = settings.value(SETUP_DIALOG_SIZE_SETTING, sizeHint() ).toSize(); resize(winSize); move(pos); }
bool FskinCreator::create(const QString& path, int width, int height, QImage& img) { if (!QFile::exists(path)) return false; KTar tar(path); if (!tar.open(QIODevice::ReadOnly)) return false; QStringList entries = tar.directory()->entries(); if (entries.count() != 1) return false; const KArchiveEntry* entry = tar.directory()->entry(entries.first()); if (!entry->isDirectory()) return false; const KArchiveDirectory* subdir = static_cast<const KArchiveDirectory*>(entry); const KArchiveEntry* skinconf_entry = subdir->entry("fcitx_skin.conf"); const KArchiveFile* skinconf = static_cast<const KArchiveFile*>(skinconf_entry); if (!skinconf) return false; QByteArray data = skinconf->data(); /// parse ini file content bool skinfont = false; bool skininputbar = false; QPixmap skin; QString resizemode; /// margins int ml = 0, mr = 0, mt = 0, mb = 0; /// font size QFont font; QColor color_en; QColor color_label; QColor color_ch_1st; /// text y position int yen = 0, ych = 0; /// cursor color QColor color_cursor; /// back arrow QPixmap barrow; int xba = 0, yba = 0; /// forward arrow QPixmap farrow; int xfa = 0, yfa = 0; QTextStream ss(data); QString line; QString key, value; do { line = ss.readLine(); if (line.isEmpty() || line.at(0) == '#') continue; if (line.at(0) == '[') { skinfont = (line == "[SkinFont]"); skininputbar = (line == "[SkinInputBar]"); continue; } if (!line.contains('=')) continue; key = line.split('=').at(0); value = line.split('=').at(1); if (value.isEmpty()) continue; if (skinfont) { if (key == "FontSize") { font.setPixelSize(value.toInt()); } else if (key == "InputColor") { color_en = value2color(value); } else if (key == "IndexColor") { color_label = value2color(value); } else if (key == "FirstCandColor") { color_ch_1st = value2color(value); } else if (key == "UserPhraseColor") { QColor color_ch_user = value2color(value); } else if (key == "OtherColor") { QColor color_ch_other = value2color(value); } } else if (skininputbar) { if (key == "BackImg") { const KArchiveEntry* e = subdir->entry(value); const KArchiveFile* pix = static_cast<const KArchiveFile*>(e); if (pix) skin.loadFromData(pix->data()); } else if (key == "Resize") { resizemode = value; } else if (key == "MarginLeft") { ml = value.toInt(); } else if (key == "MarginRight") { mr = value.toInt(); } else if (key == "MarginTop") { mt = value.toInt(); } else if (key == "MarginBottom") { mb = value.toInt(); } else if (key == "InputPos") { yen = value.toInt(); } else if (key == "OutputPos") { ych = value.toInt(); } else if (key == "CursorColor") { color_cursor = value2color(value); } else if (key == "BackArrow") { const KArchiveEntry* e = subdir->entry(value); const KArchiveFile* pix = static_cast<const KArchiveFile*>(e); if (pix) barrow.loadFromData(pix->data()); } else if (key == "ForwardArrow") { const KArchiveEntry* e = subdir->entry(value); const KArchiveFile* pix = static_cast<const KArchiveFile*>(e); if (pix) farrow.loadFromData(pix->data()); } else if (key == "BackArrowX") { xba = value.toInt(); } else if (key == "BackArrowY") { yba = value.toInt(); } else if (key == "ForwardArrowX") { xfa = value.toInt(); } else if (key == "ForwardArrowY") { yfa = value.toInt(); } } } while (!line.isNull()); int fontHeight = QFontMetrics(font).height(); int pinyinw = QFontMetrics(font).width("ABC pinyin"); int zhongwenw = QFontMetrics(font).width("1candidate"); /// save target size int targetHeight = height; int targetWidth = width; height = mt + ych + mb; width = qMax(ml + pinyinw + mr, ml + zhongwenw + mr); width = qMax(width, targetWidth); width = qMax(width, skin.width()); yen = mt + yen - fontHeight; ych = mt + ych - fontHeight; QPixmap pixmap(width, height); pixmap.fill(Qt::transparent); QPainter p(&pixmap); /// corners lt, lb, rt, rb p.drawPixmap(0, 0, skin, 0, 0, ml, mt); p.drawPixmap(0, height - mb, skin, 0, skin.height() - mb, ml, mb); p.drawPixmap(width - mr, 0, skin, skin.width() - mr, 0, mr, mt); p.drawPixmap(width - mr, height - mb, skin, skin.width() - mr, skin.height() - mb, mr, mb); /// left right p.drawPixmap(0, mt, ml, height - mt - mb, skin, 0, mt, ml, skin.height() - mt - mb); p.drawPixmap(width - mr, mt, mr, height - mt - mb, skin, skin.width() - mr, mt, mr, skin.height() - mt - mb); /// top bottom p.drawPixmap(ml, 0, width - ml - mr, mt, skin, ml, 0, skin.width() - ml - mr, mt); p.drawPixmap(ml, height - mb, width - ml - mr, mb, skin, ml, skin.height() - mb, skin.width() - ml - mr, mb); /// middle p.drawPixmap(ml, mt, width - ml - mr, height - mt - mb, skin, ml, mt, skin.width() - ml - mr, skin.height() - mt - mb); /// draw arrows p.drawPixmap(width - xba, yba, barrow); p.drawPixmap(width - xfa, yfa, farrow); /// draw preedit / aux text p.setFont(font); p.setPen(color_en); p.drawText(ml, yen, pinyinw, fontHeight, Qt::AlignCenter, "ABC pinyin"); p.drawLine(ml + pinyinw, yen, ml + pinyinw, yen + fontHeight); /// draw lookup table p.setPen(color_label); int labelw = p.fontMetrics().width("1"); p.drawText(ml, ych, labelw, fontHeight, Qt::AlignCenter, "1"); p.setPen(color_ch_1st); int candidatew = p.fontMetrics().width("candidate"); p.drawText(ml + labelw, ych, candidatew, fontHeight, Qt::AlignCenter, "candidate"); p.end(); if (targetWidth < width || targetHeight < height) { pixmap = pixmap.scaled(targetWidth, targetHeight, Qt::KeepAspectRatio); } img = pixmap.toImage(); return true; }
/*! Draw a color bar into a rectangle \param painter Painter \param colorMap Color map \param interval Value range \param scaleMap Scale map \param orientation Orientation \param rect Traget rectangle */ void QwtPainter::drawColorBar( QPainter *painter, const QwtColorMap &colorMap, const QwtInterval &interval, const QwtScaleMap &scaleMap, Qt::Orientation orientation, const QRectF &rect ) { QVector<QRgb> colorTable; if ( colorMap.format() == QwtColorMap::Indexed ) colorTable = colorMap.colorTable( interval ); QColor c; const QRect devRect = rect.toAlignedRect(); /* We paint to a pixmap first to have something scalable for printing ( f.e. in a Pdf document ) */ QPixmap pixmap( devRect.size() ); QPainter pmPainter( &pixmap ); pmPainter.translate( -devRect.x(), -devRect.y() ); if ( orientation == Qt::Horizontal ) { QwtScaleMap sMap = scaleMap; sMap.setPaintInterval( rect.left(), rect.right() ); for ( int x = devRect.left(); x <= devRect.right(); x++ ) { const double value = sMap.invTransform( x ); if ( colorMap.format() == QwtColorMap::RGB ) c.setRgba( colorMap.rgb( interval, value ) ); else c = colorTable[colorMap.colorIndex( interval, value )]; pmPainter.setPen( c ); pmPainter.drawLine( x, devRect.top(), x, devRect.bottom() ); } } else // Vertical { QwtScaleMap sMap = scaleMap; sMap.setPaintInterval( rect.bottom(), rect.top() ); for ( int y = devRect.top(); y <= devRect.bottom(); y++ ) { const double value = sMap.invTransform( y ); if ( colorMap.format() == QwtColorMap::RGB ) c.setRgb( colorMap.rgb( interval, value ) ); else c = colorTable[colorMap.colorIndex( interval, value )]; pmPainter.setPen( c ); pmPainter.drawLine( devRect.left(), y, devRect.right(), y ); } } pmPainter.end(); drawPixmap( painter, rect, pixmap ); }
void tst_QStandardItem::getSetData() { QStandardItem item; for (int x = 0; x < 2; ++x) { for (int i = 1; i <= 2; ++i) { QString text = QString("text %0").arg(i); item.setText(text); QCOMPARE(item.text(), text); QPixmap pixmap(32, 32); pixmap.fill((i == 1) ? Qt::red : Qt::green); QIcon icon(pixmap); item.setIcon(icon); QCOMPARE(item.icon(), icon); QString toolTip = QString("toolTip %0").arg(i); item.setToolTip(toolTip); QCOMPARE(item.toolTip(), toolTip); QString statusTip = QString("statusTip %0").arg(i); item.setStatusTip(statusTip); QCOMPARE(item.statusTip(), statusTip); QString whatsThis = QString("whatsThis %0").arg(i); item.setWhatsThis(whatsThis); QCOMPARE(item.whatsThis(), whatsThis); QSize sizeHint(64*i, 48*i); item.setSizeHint(sizeHint); QCOMPARE(item.sizeHint(), sizeHint); QFont font; item.setFont(font); QCOMPARE(item.font(), font); Qt::Alignment textAlignment((i == 1) ? Qt::AlignLeft|Qt::AlignVCenter : Qt::AlignRight); item.setTextAlignment(textAlignment); QCOMPARE(item.textAlignment(), textAlignment); QColor backgroundColor((i == 1) ? Qt::blue : Qt::yellow); item.setBackground(backgroundColor); QCOMPARE(item.background().color(), backgroundColor); QColor textColor((i == i) ? Qt::green : Qt::cyan); item.setForeground(textColor); QCOMPARE(item.foreground().color(), textColor); Qt::CheckState checkState((i == 1) ? Qt::PartiallyChecked : Qt::Checked); item.setCheckState(checkState); QCOMPARE(item.checkState(), checkState); QString accessibleText = QString("accessibleText %0").arg(i); item.setAccessibleText(accessibleText); QCOMPARE(item.accessibleText(), accessibleText); QString accessibleDescription = QString("accessibleDescription %0").arg(i); item.setAccessibleDescription(accessibleDescription); QCOMPARE(item.accessibleDescription(), accessibleDescription); QCOMPARE(item.text(), text); QCOMPARE(item.icon(), icon); QCOMPARE(item.toolTip(), toolTip); QCOMPARE(item.statusTip(), statusTip); QCOMPARE(item.whatsThis(), whatsThis); QCOMPARE(item.sizeHint(), sizeHint); QCOMPARE(item.font(), font); QCOMPARE(item.textAlignment(), textAlignment); QCOMPARE(item.background().color(), backgroundColor); QCOMPARE(item.foreground().color(), textColor); QCOMPARE(item.checkState(), checkState); QCOMPARE(item.accessibleText(), accessibleText); QCOMPARE(item.accessibleDescription(), accessibleDescription); QCOMPARE(qvariant_cast<QString>(item.data(Qt::DisplayRole)), text); QCOMPARE(qvariant_cast<QIcon>(item.data(Qt::DecorationRole)), icon); QCOMPARE(qvariant_cast<QString>(item.data(Qt::ToolTipRole)), toolTip); QCOMPARE(qvariant_cast<QString>(item.data(Qt::StatusTipRole)), statusTip); QCOMPARE(qvariant_cast<QString>(item.data(Qt::WhatsThisRole)), whatsThis); QCOMPARE(qvariant_cast<QSize>(item.data(Qt::SizeHintRole)), sizeHint); QCOMPARE(qvariant_cast<QFont>(item.data(Qt::FontRole)), font); QCOMPARE(qvariant_cast<int>(item.data(Qt::TextAlignmentRole)), int(textAlignment)); QCOMPARE(qvariant_cast<QBrush>(item.data(Qt::BackgroundColorRole)), QBrush(backgroundColor)); QCOMPARE(qvariant_cast<QBrush>(item.data(Qt::BackgroundRole)), QBrush(backgroundColor)); QCOMPARE(qvariant_cast<QBrush>(item.data(Qt::TextColorRole)), QBrush(textColor)); QCOMPARE(qvariant_cast<QBrush>(item.data(Qt::ForegroundRole)), QBrush(textColor)); QCOMPARE(qvariant_cast<int>(item.data(Qt::CheckStateRole)), int(checkState)); QCOMPARE(qvariant_cast<QString>(item.data(Qt::AccessibleTextRole)), accessibleText); QCOMPARE(qvariant_cast<QString>(item.data(Qt::AccessibleDescriptionRole)), accessibleDescription); item.setBackground(pixmap); QCOMPARE(item.background().texture(), pixmap); QCOMPARE(qvariant_cast<QBrush>(item.data(Qt::BackgroundRole)).texture(), pixmap); } item.setData(QVariant(), Qt::DisplayRole); item.setData(QVariant(), Qt::DecorationRole); item.setData(QVariant(), Qt::ToolTipRole); item.setData(QVariant(), Qt::StatusTipRole); item.setData(QVariant(), Qt::WhatsThisRole); item.setData(QVariant(), Qt::SizeHintRole); item.setData(QVariant(), Qt::FontRole); item.setData(QVariant(), Qt::TextAlignmentRole); item.setData(QVariant(), Qt::BackgroundRole); item.setData(QVariant(), Qt::ForegroundRole); item.setData(QVariant(), Qt::CheckStateRole); item.setData(QVariant(), Qt::AccessibleTextRole); item.setData(QVariant(), Qt::AccessibleDescriptionRole); QCOMPARE(item.data(Qt::DisplayRole), QVariant()); QCOMPARE(item.data(Qt::DecorationRole), QVariant()); QCOMPARE(item.data(Qt::ToolTipRole), QVariant()); QCOMPARE(item.data(Qt::StatusTipRole), QVariant()); QCOMPARE(item.data(Qt::WhatsThisRole), QVariant()); QCOMPARE(item.data(Qt::SizeHintRole), QVariant()); QCOMPARE(item.data(Qt::FontRole), QVariant()); QCOMPARE(item.data(Qt::TextAlignmentRole), QVariant()); QCOMPARE(item.data(Qt::BackgroundColorRole), QVariant()); QCOMPARE(item.data(Qt::BackgroundRole), QVariant()); QCOMPARE(item.data(Qt::TextColorRole), QVariant()); QCOMPARE(item.data(Qt::ForegroundRole), QVariant()); QCOMPARE(item.data(Qt::CheckStateRole), QVariant()); QCOMPARE(item.data(Qt::AccessibleTextRole), QVariant()); QCOMPARE(item.data(Qt::AccessibleDescriptionRole), QVariant()); } }
void LegendItem::paint(QPainter *painter) { if (!isVisible()) { return; } RelationList legendItems; if (_auto) { legendItems = plot()->renderItem(PlotRenderItem::Cartesian)->relationList(); } else { legendItems = _relations; } int count = legendItems.count(); if (count <= 0) { // no legend or box if there are no legend items return; } QList<DrawnLegendItem> legendPixmaps; QSize legendSize(0, 0); QFont font(_font); font.setPointSizeF(view()->viewScaledFontSize(_fontScale)); // generate string list of relation names QStringList names; bool allAuto = true; bool sameX = true; bool sameYUnits = true; LabelInfo label_info = legendItems.at(0)->xLabelInfo(); QString yUnits = legendItems.at(0)->yLabelInfo().units; for (int i = 0; i<count; i++) { RelationPtr relation = legendItems.at(i); if (relation->descriptiveNameIsManual()) { allAuto = false; } if (relation->xLabelInfo() != label_info) { sameX = false; } // sameYUnits is false if any non empty units are defined differently. if (yUnits.isEmpty()) { yUnits = relation->yLabelInfo().units; } else if (relation->yLabelInfo().units != yUnits) { if (!relation->yLabelInfo().units.isEmpty()) { sameYUnits = false; } } } if (!allAuto) { for (int i = 0; i<count; i++) { names.append(legendItems.at(i)->descriptiveName()); } } else { for (int i = 0; i<count; i++) { RelationPtr relation = legendItems.at(i); QString label = relation->titleInfo().singleRenderItemLabel(); if (label.isEmpty()) { label_info = relation->yLabelInfo(); QString y_label = label_info.name; if (!sameYUnits) { if (!label_info.units.isEmpty()) { y_label = i18n("%1 \\[%2\\]").arg(y_label).arg(label_info.units); } } if (!y_label.isEmpty()) { LabelInfo xlabel_info = relation->xLabelInfo(); if (!sameX) { label = i18n("%1 vs %2").arg(y_label).arg(xlabel_info.name); } else if (xlabel_info.quantity.isEmpty()) { label = y_label; } else if (xlabel_info.quantity != xlabel_info.name) { label = i18n("%1 vs %2").arg(y_label).arg(xlabel_info.name); } else { label = y_label; } } else { label = relation->descriptiveName(); } } int i_dup = names.indexOf(label); if (i_dup<0) { names.append(label); } else { RelationPtr dup_relation = legendItems.at(i_dup); if (!dup_relation->yLabelInfo().file.isEmpty()) { names.replace(i_dup, label + " (" + dup_relation->yLabelInfo().file + ')'); } if (!relation->yLabelInfo().file.isEmpty()) { names.append(label + " (" + relation->yLabelInfo().file + ')'); } } } } for (int i = 0; i<count; i++) { RelationPtr relation = legendItems.at(i); DrawnLegendItem item; item.pixmap = QPixmap(LEGENDITEMMAXWIDTH, LEGENDITEMMAXHEIGHT); item.size = paintRelation(names.at(i), relation, &item.pixmap, font); if (_verticalDisplay) { legendSize.setWidth(qMax(legendSize.width(), item.size.width())); legendSize.setHeight(legendSize.height() + item.size.height()); } else { legendSize.setHeight(qMax(legendSize.height(), item.size.height())); legendSize.setWidth(legendSize.width() + item.size.width()); } legendPixmaps.append(item); } int x = rect().left(); int y = rect().top(); painter->save(); if (!_title.isEmpty()) { // Paint the title Label::Parsed *parsed = Label::parse(_title); if (parsed) { painter->save(); QPixmap pixmap(400, 100); pixmap.fill(Qt::transparent); QPainter pixmapPainter(&pixmap); Label::RenderContext rc(font, &pixmapPainter); QFontMetrics fm(font); rc.y = fm.ascent(); Label::renderLabel(rc, parsed->chunk, false); int startPoint = qMax(0, (legendSize.width() / 2) - (rc.x / 2)); int paddingValue = fm.height() / 4; setViewRect(viewRect().x(), viewRect().y(), qMax(rc.x, legendSize.width()), rc.y + legendSize.height() + paddingValue * 3); painter->drawRect(rect()); painter->drawPixmap(QPoint(x + startPoint, y + paddingValue), pixmap, QRect(0, 0, rc.x, fm.height())); painter->restore(); y += fm.height() + (paddingValue *2); delete parsed; parsed = 0; } } else { // No Title setViewRect(viewRect().x(), viewRect().y(), legendSize.width(), legendSize.height()); painter->drawRect(rect()); } foreach(const DrawnLegendItem &item, legendPixmaps) { painter->drawPixmap(QPoint(x, y), item.pixmap, QRect(0, 0, item.size.width(), item.size.height())); if (_verticalDisplay) { y += item.size.height(); } else { x += item.size.width(); } }
_newAct->setEnabled(false); connect(_newAct, SIGNAL(triggered()), this, SLOT(sNew())); addAction(_newAct); connect(this, SIGNAL(valid(bool)), _infoAct, SLOT(setEnabled(bool))); _menuLabel = new QLabel(this); // Menu set up _menu = 0; _menuLabel->setPixmap(QPixmap(":/widgets/images/magnifier.png")); _menuLabel->installEventFilter(this); int height = minimumSizeHint().height(); QString sheet = QLatin1String("QLineEdit{ padding-right: "); sheet += QString::number(_menuLabel->pixmap()->width() + 6); sheet += QLatin1String(";}"); setStyleSheet(sheet); // Little hack. Somehow style sheet makes widget short. Put back height. setMinimumHeight(height); // Set default menu with standard actions QMenu* menu = new QMenu; menu->addAction(_listAct); menu->addAction(_searchAct); menu->addSeparator(); menu->addAction(_infoAct); setMenu(menu); connect(this, SIGNAL(valid(bool)), this, SLOT(sUpdateMenu())); connect(menu, SIGNAL(aboutToShow()), this, SLOT(sUpdateMenu()));
void MyShip::cnstrct_shldpxmp() { shpshld->setPos(pos().x() + (pixmap().width() / 2) - (shpshld->pixmap().width() / 2), pos().y() + (pixmap().height() / 2) - (shpshld->pixmap().height() / 2)); }
NotificationDialog::NotificationDialog(Notification *notification, QWidget *parent) : QDialog(parent), m_notification(notification), m_closeLabel(nullptr), m_closeTimer(0) { QFrame *notificationFrame(new QFrame(this)); notificationFrame->setObjectName(QLatin1String("notificationFrame")); notificationFrame->setStyleSheet(QLatin1String("#notificationFrame {padding:5px;border:1px solid #CCC;border-radius:10px;background:#F0F0f0;}")); notificationFrame->setCursor(QCursor(Qt::PointingHandCursor)); notificationFrame->installEventFilter(this); QBoxLayout *mainLayout(new QBoxLayout(QBoxLayout::LeftToRight)); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setSpacing(0); mainLayout->setSizeConstraint(QLayout::SetMinimumSize); mainLayout->addWidget(notificationFrame); QLabel *iconLabel(new QLabel(this)); iconLabel->setPixmap(ThemesManager::createIcon(QLatin1String("otter-browser-32")).pixmap(32, 32)); iconLabel->setStyleSheet(QLatin1String("padding:5px;")); QLabel *messageLabel(new QLabel(this)); messageLabel->setText(m_notification->getMessage()); messageLabel->setStyleSheet(QLatin1String("padding:5px;font-size:13px;")); messageLabel->setWordWrap(true); QStyleOption option; option.rect = QRect(0, 0, 16, 16); QPixmap pixmap(16, 16); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &option, &painter, this); m_closeLabel = new QLabel(notificationFrame); m_closeLabel->setToolTip(tr("Close")); m_closeLabel->setPixmap(pixmap); m_closeLabel->setAlignment(Qt::AlignTop); m_closeLabel->setMargin(5); m_closeLabel->installEventFilter(this); QBoxLayout *notificationLayout(new QBoxLayout(QBoxLayout::LeftToRight)); notificationLayout->setContentsMargins(0, 0, 0, 0); notificationLayout->setSpacing(0); notificationLayout->setSizeConstraint(QLayout::SetMinimumSize); notificationLayout->addWidget(iconLabel); notificationLayout->addWidget(messageLabel); notificationLayout->addWidget(m_closeLabel); notificationFrame->setLayout(notificationLayout); setLayout(mainLayout); setFixedWidth(400); setMinimumHeight(50); setMaximumHeight(150); setWindowOpacity(0); setWindowFlags(Qt::WindowStaysOnTopHint | Qt::Tool | Qt::FramelessWindowHint); setFocusPolicy(Qt::NoFocus); setAttribute(Qt::WA_DeleteOnClose, true); setAttribute(Qt::WA_ShowWithoutActivating, true); setAttribute(Qt::WA_TranslucentBackground, true); adjustSize(); m_animation = new QPropertyAnimation(this, QStringLiteral("windowOpacity").toLatin1()); m_animation->setDuration(500); m_animation->setStartValue(0.0); m_animation->setEndValue(1.0); m_animation->start(); const int visibilityDuration(SettingsManager::getOption(SettingsManager::Interface_NotificationVisibilityDurationOption).toInt()); if (visibilityDuration > 0) { m_closeTimer = startTimer(visibilityDuration * 1000); } }
void SearchResultItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const SearchResultListModel *model = static_cast<const SearchResultListModel*>(index.model()); QBrush backBrush; bool selected = false; FileSearchResult file = getSearchResult(index); if (option.state & (QStyle::State_HasFocus | QStyle::State_Selected)) { backBrush = QColor(kFileItemBackgroundColorHighlighted); selected = true; } else { backBrush = QColor(kFileItemBackgroundColor); } // // draw item's background // painter->save(); painter->fillRect(option.rect, backBrush); painter->restore(); QIcon icon = model->data(index, Qt::DecorationRole).value<QIcon>(); // get the device pixel radio from current painter device int scale_factor = 1; #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) scale_factor = painter->device()->devicePixelRatio(); #endif // QT5 QPixmap pixmap(icon.pixmap(QSize(kFileIconWidth, kFileIconHeight) * scale_factor)); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) if (pixmap.size() != QSize(kFileIconWidth, kFileIconHeight)) pixmap.setDevicePixelRatio(scale_factor); #endif // QT5 // // paint file icon // QPoint file_icon_pos(kMarginLeft + kPadding, kMarginTop + kPadding); file_icon_pos += option.rect.topLeft(); painter->save(); painter->drawPixmap(file_icon_pos, pixmap); painter->restore(); // Calculate the file column by the delta of mainwindow's width QString title = file.name; const int file_name_width = kFileNameWidth + seafApplet->mainWindow()->width() - seafApplet->mainWindow()->minimumWidth(); painter->save(); QPoint file_name_pos = file_icon_pos + QPoint(kFileIconWidth + kMarginBetweenFileIconAndName, -kPadding); QRect file_name_rect(file_name_pos, QSize(file_name_width, kFileNameHeight)); painter->setPen(QColor(selected ? kFileNameColorHighlighted : kFileNameColor)); painter->setFont(changeFontSize(painter->font(), kFileNameFontSize)); painter->drawText(file_name_rect, Qt::AlignLeft | Qt::AlignTop, fitTextToWidth(title, option.font, file_name_width), &file_name_rect); painter->restore(); // // Paint repo_name // int count_of_splash = file.fullpath.endsWith("/") ? 2 : 1; QString subtitle = file.fullpath.mid(1, file.fullpath.size() - count_of_splash - file.name.size()); if (!subtitle.isEmpty()) subtitle = file.repo_name + "/" + subtitle.left(subtitle.size() - 1); else subtitle = file.repo_name; painter->save(); QPoint file_desc_pos = file_name_rect.bottomLeft() + QPoint(0, kPadding / 2); QRect file_desc_rect(file_desc_pos, QSize(file_name_width, kSubtitleHeight)); painter->setFont(changeFontSize(painter->font(), kSubtitleFontSize)); painter->setPen(QColor(selected ? kSubtitleColorHighlighted : kSubtitleColor)); painter->drawText(file_desc_rect, Qt::AlignLeft | Qt::AlignTop, fitTextToWidth(subtitle, option.font, file_name_width), &file_desc_rect); painter->restore(); // // Paint file description // QString size, mtime; size = readableFileSize(file.size); mtime = translateCommitTime(file.last_modified); QString extra_title = size + " " + mtime; painter->save(); QPoint file_extra_pos = file_desc_rect.bottomLeft() + QPoint(0, kPadding / 2 + 2); QRect file_extra_rect(file_extra_pos, QSize(file_name_width, kSubtitleHeight)); painter->setFont(changeFontSize(painter->font(), kSubtitleFontSize)); painter->setPen(QColor(selected ? kSubtitleColorHighlighted : kSubtitleColor)); painter->drawText(file_extra_rect, Qt::AlignLeft | Qt::AlignTop, fitTextToWidth(extra_title, option.font, file_name_width), &file_extra_rect); painter->restore(); // // Draw the bottom border lines // painter->save(); painter->setPen(QPen(QColor(kItemBottomBorderColor), 1, Qt::SolidLine)); painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); painter->restore(); }
/** This function displays text and color formatting in order to help the user understand what channels have not yet been configured. */ bool ConfigGroundVehicleWidget::throwConfigError(QString airframeType) { // Initialize configuration error flag bool error = false; // Create a red block. All combo boxes are the same size, so any one should do as a model int size = m_aircraft->gvMotor1ChannelBox->style()->pixelMetric(QStyle::PM_SmallIconSize); QPixmap pixmap(size, size); pixmap.fill(QColor("red")); if (airframeType == "GroundVehicleCar") { // Car if (m_aircraft->gvMotor1ChannelBox->currentText() == "None" && m_aircraft->gvMotor2ChannelBox->currentText() == "None") { m_aircraft->gvMotor1ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes m_aircraft->gvMotor2ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes error = true; } else { m_aircraft->gvMotor1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes m_aircraft->gvMotor2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } if (m_aircraft->gvSteering1ChannelBox->currentText() == "None" && m_aircraft->gvSteering2ChannelBox->currentText() == "None") { m_aircraft->gvSteering1ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes m_aircraft->gvSteering2ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes error = true; } else { m_aircraft->gvSteering1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes m_aircraft->gvSteering2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } } else if (airframeType == "GroundVehicleDifferential") { // Tank if (m_aircraft->gvMotor1ChannelBox->currentText() == "None" || m_aircraft->gvMotor2ChannelBox->currentText() == "None") { m_aircraft->gvMotor1ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes m_aircraft->gvMotor2ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes error = true; } else { m_aircraft->gvMotor1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes m_aircraft->gvMotor2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } // Always reset m_aircraft->gvSteering1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes m_aircraft->gvSteering2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } else if (airframeType == "GroundVehicleMotorcycle") { // Motorcycle if (m_aircraft->gvMotor2ChannelBox->currentText() == "None") { m_aircraft->gvMotor2ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes error = true; } else { m_aircraft->gvMotor2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } if (m_aircraft->gvSteering1ChannelBox->currentText() == "None" && m_aircraft->gvSteering2ChannelBox->currentText() == "None") { m_aircraft->gvSteering1ChannelBox->setItemData(0, pixmap, Qt::DecorationRole); // Set color palettes error = true; } else { m_aircraft->gvSteering1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } // Always reset m_aircraft->gvMotor1ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes m_aircraft->gvSteering2ChannelBox->setItemData(0, 0, Qt::DecorationRole); // Reset color palettes } if (error) { m_aircraft->gvStatusLabel->setText(QString("<font color='red'>ERROR: Assign all necessary channels</font>")); } return error; }
/*! * \brief OMEditApplication::OMEditApplication * \param argc * \param argv * \param threadData */ OMEditApplication::OMEditApplication(int &argc, char **argv, threadData_t* threadData) : QApplication(argc, argv) { // set the stylesheet setStyleSheet("file:///:/Resources/css/stylesheet.qss"); #if !(QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) QTextCodec::setCodecForTr(QTextCodec::codecForName(Helper::utf8.toLatin1().data())); QTextCodec::setCodecForCStrings(QTextCodec::codecForName(Helper::utf8.toLatin1().data())); #endif #ifndef WIN32 QTextCodec::setCodecForLocale(QTextCodec::codecForName(Helper::utf8.toLatin1().data())); #endif setAttribute(Qt::AA_DontShowIconsInMenus, false); // Localization //*a.severin/ add localization const char *omhome = getenv("OPENMODELICAHOME"); #ifdef WIN32 if (!omhome) { QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error), GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok); quit(); exit(1); } #else /* unix */ omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME; #endif QSettings *pSettings = Utilities::getApplicationSettings(); QLocale settingsLocale = QLocale(pSettings->value("language").toString()); settingsLocale = settingsLocale.name() == "C" ? pSettings->value("language").toLocale() : settingsLocale; QString locale = settingsLocale.name().isEmpty() ? QLocale::system().name() : settingsLocale.name(); /* Set the default locale of the application so that QSpinBox etc show values according to the locale. * Set OMEdit locale to C so that we get dot as decimal separator instead of comma. */ QLocale::setDefault(QLocale::c()); QString translationDirectory = omhome + QString("/share/omedit/nls"); // install Qt's default translations QTranslator *pQtTranslator = new QTranslator(this); #ifdef Q_OS_WIN pQtTranslator->load("qt_" + locale, translationDirectory); #else pQtTranslator->load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); #endif installTranslator(pQtTranslator); // install application translations QTranslator *pTranslator = new QTranslator(this); pTranslator->load("OMEdit_" + locale, translationDirectory); installTranslator(pTranslator); // Splash Screen QPixmap pixmap(":/Resources/icons/omedit_splashscreen.png"); SplashScreen *pSplashScreen = SplashScreen::instance(); pSplashScreen->setPixmap(pixmap); pSplashScreen->show(); Helper::initHelperVariables(); /* Force C-style doubles */ setlocale(LC_NUMERIC, "C"); // if user has requested to open the file by passing it in argument then, bool debug = false; QString fileName = ""; QStringList fileNames; if (arguments().size() > 1) { for (int i = 1; i < arguments().size(); i++) { if (strncmp(arguments().at(i).toStdString().c_str(), "--Debug=",8) == 0) { QString debugArg = arguments().at(i); debugArg.remove("--Debug="); if (0 == strcmp("true", debugArg.toStdString().c_str())) { debug = true; } else { debug = false; } } else { fileName = arguments().at(i); if (!fileName.isEmpty()) { // if path is relative make it absolute QFileInfo file (fileName); QString absoluteFileName = fileName; if (file.isRelative()) { absoluteFileName = QString("%1/%2").arg(QDir::currentPath()).arg(fileName); } absoluteFileName = absoluteFileName.replace("\\", "/"); if (QFile::exists(absoluteFileName)) { fileNames << absoluteFileName; } else { printf("Invalid command line argument: %s %s\n", fileName.toStdString().c_str(), absoluteFileName.toStdString().c_str()); } } } } } // MainWindow Initialization MainWindow *pMainwindow = MainWindow::instance(debug); pMainwindow->setUpMainWindow(threadData); if (pMainwindow->getExitApplicationStatus()) { // if there is some issue in running the application. quit(); exit(1); } // open the files passed as command line arguments foreach (QString fileName, fileNames) { pMainwindow->getLibraryWidget()->openFile(fileName); }
QVariant QSPixmapClass::toVariant( const QSObject *obj, QVariant::Type ) const { return *pixmap( obj ); }
/** * \brief Entry function. * \param[in] argc - number of arguments * \param[in] argv[] - argumnet list * \return true if all went well */ int main(int argc, char *argv[]) { bool debug = false; bool remoteServers = true; QStringList localModules; QVector<MainWindow::Module> remoteModules; //process arguments for(int i=1; i<argc; i++) { QString cmd(argv[i]); if(cmd=="--debug") { debug = true; } else if(cmd=="--localMode") { remoteServers = false; } else if(cmd=="--localModules") // e.g. --localModules som,mtrnn,esn,tracker,era { QString module = argv[i+1]; //read modules if(!module.contains("--") || !module.isEmpty()) { localModules = module.split(","); i++; } } else if(cmd=="--remoteModules") // e.g. --remoteModules 1=som,mtrnn,esn 2=tracker,era { QString command = argv[i+1]; bool isNumber; //check if any modules were added at all if(!command.contains("--")) { //read modules until new parameter is found or no more parameters exist while(!command.contains("--") && i<argc-1) { i++; QStringList modules = command.split("="); if(!modules.empty()) { MainWindow::Module serverModule; modules.at(0).toInt(&isNumber); //check if the argument starts with server id if(isNumber) { serverModule.serverID = modules.at(0); serverModule.modules = modules.at(1).split(","); remoteModules.push_back(serverModule); } } command = argv[i+1]; } } } } //initialises message handeler if(!debug) { qInstallMsgHandler(customMessageHandler); } //current Aquila verions QString version = "Aquila 2.0"; //localhost name QString hostName = QHostInfo::localHostName(); //minimum version of YARP required for full support QString yarpVersion = "2.3.20"; //add active developers to the list QStringList developers; developers<<" Martin Peniak"<<" & Anthony Morse"; //initialise YARP yarp::os::Network yarp; //initialises Aquila and loads its icon QApplication *a = new QApplication(argc, argv); a->setWindowIcon(QPixmap(":/images/icon.png")); a->setAttribute(Qt::AA_X11InitThreads); //initialise splash screen QPixmap pixmap(":/images/splash.png"); SplashScreen *splash = new SplashScreen(pixmap, 4); splash->setFont(QFont("Ariel", 8, QFont::Bold)); splash->show(); //initialise GUI, probe yarpservers, its modules and add local modules to GUI MainWindow *w = new MainWindow(0, version, hostName, yarpVersion); splash->showMessage(QString("Initialising ")+version,Qt::AlignLeft | Qt::AlignBottom,Qt::white); QObject::connect(a, SIGNAL(aboutToQuit()), w, SLOT(aboutToQuit())); a->processEvents(); splash->showMessage(QObject::tr("Detecting available modules on the local network"),Qt::AlignLeft | Qt::AlignBottom,Qt::white); w->probeServers(remoteServers); a->processEvents(); //start local modules if(!localModules.isEmpty()) { splash->showMessage(QObject::tr("Starting local modules"),Qt::AlignLeft | Qt::AlignBottom,Qt::white); w->addLocalModules(localModules); a->processEvents(); } //start remote modules if(!remoteModules.isEmpty()) { if(remoteServers) { splash->showMessage(QObject::tr("Starting remote modules"),Qt::AlignLeft | Qt::AlignBottom,Qt::white); w->addRemoteModules(remoteModules); a->processEvents(); } else { qWarning(" - main_gui: '--localMode' argument prevented remote modules from loading during startup"); } } //load graphial user interface, show credits and close the splash splash->showMessage(QObject::tr("Loading graphical user interface"),Qt::AlignLeft | Qt::AlignBottom,Qt::white); a->processEvents(); QString credits("Developed by"); for(int i=0; i<developers.size(); i++) { credits.append(developers.at(i)); } splash->showMessage(credits,Qt::AlignLeft | Qt::AlignBottom,Qt::white); a->processEvents(); splash->finish(w); //show graphial user interface w->show(); return a->exec(); }
/*! Initialize \a option with the values using the index \a index. This method is useful for subclasses when they need a QStyleOptionViewItem, but don't want to fill in all the information themselves. \sa QStyleOption::initFrom() */ void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const { QVariant value = index.data(Qt::FontRole); if (value.isValid() && !value.isNull()) { option->font = qvariant_cast<QFont>(value).resolve(option->font); option->fontMetrics = QFontMetrics(option->font); } value = index.data(Qt::TextAlignmentRole); if (value.isValid() && !value.isNull()) option->displayAlignment = Qt::Alignment(value.toInt()); value = index.data(Qt::ForegroundRole); if (value.canConvert<QBrush>()) option->palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value)); option->index = index; value = index.data(Qt::CheckStateRole); if (value.isValid() && !value.isNull()) { option->features |= QStyleOptionViewItem::HasCheckIndicator; option->checkState = static_cast<Qt::CheckState>(value.toInt()); } value = index.data(Qt::DecorationRole); if (value.isValid() && !value.isNull()) { option->features |= QStyleOptionViewItem::HasDecoration; switch (value.type()) { case QVariant::Icon: { option->icon = qvariant_cast<QIcon>(value); QIcon::Mode mode; if (!(option->state & QStyle::State_Enabled)) mode = QIcon::Disabled; else if (option->state & QStyle::State_Selected) mode = QIcon::Selected; else mode = QIcon::Normal; QIcon::State state = option->state & QStyle::State_Open ? QIcon::On : QIcon::Off; QSize actualSize = option->icon.actualSize(option->decorationSize, mode, state); // For highdpi icons actualSize might be larger than decorationSize, which we don't want. Clamp it to decorationSize. option->decorationSize = QSize(qMin(option->decorationSize.width(), actualSize.width()), qMin(option->decorationSize.height(), actualSize.height())); break; } case QVariant::Color: { QPixmap pixmap(option->decorationSize); pixmap.fill(qvariant_cast<QColor>(value)); option->icon = QIcon(pixmap); break; } case QVariant::Image: { QImage image = qvariant_cast<QImage>(value); option->icon = QIcon(QPixmap::fromImage(image)); option->decorationSize = image.size() / image.devicePixelRatio(); break; } case QVariant::Pixmap: { QPixmap pixmap = qvariant_cast<QPixmap>(value); option->icon = QIcon(pixmap); option->decorationSize = pixmap.size() / pixmap.devicePixelRatio(); break; } default: break; } } value = index.data(Qt::DisplayRole); if (value.isValid() && !value.isNull()) { option->features |= QStyleOptionViewItem::HasDisplay; option->text = displayText(value, option->locale); } option->backgroundBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole)); // disable style animations for checkboxes etc. within itemviews (QTBUG-30146) option->styleObject = 0; }
void MusicSettingWidget::initControllerParameter() { //Set init parameter ui->autoPlayCheckBox->setChecked(M_SETTING->value(MusicSettingManager::AutoPlayChoiced).toBool()); ui->backPlayCheckBox->setChecked(M_SETTING->value(MusicSettingManager::LastPlayIndexChoiced) .toStringList().first().toInt() ); if(!M_SETTING->value(MusicSettingManager::CloseEventChoiced).toBool()) { ui->minimumRadioBox->setChecked(true); } else { ui->quitRadioBox->setChecked(true); } ui->languageComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::CurrentLanIndexChoiced).toInt()); //////////////////////////////////////////////// //Set init parameter ui->showInlineCheckBox->setChecked(M_SETTING->value(MusicSettingManager::ShowInlineLrcChoiced).toBool()); ui->showDesktopCheckBox->setChecked(M_SETTING->value(MusicSettingManager::ShowDesktopLrcChoiced).toBool()); ui->showInlineCheckBox->setEnabled(false); ui->fontComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::LrcFamilyChoiced).toInt()); ui->fontSizeComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::LrcSizeChoiced).toInt() - 13); ui->fontTypeComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::LrcTypeChoiced).toInt()); if(M_SETTING->value(MusicSettingManager::LrcColorChoiced).toInt() != -1) { ui->fontDefaultColorComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::LrcColorChoiced).toInt()); } else { ui->fontDefaultColorComboBox->setCurrentIndex(-1); QPixmap pixmap(16, 16); pixmap.fill(m_lrcSelectedFg = M_SETTING->value(MusicSettingManager::LrcFgColorChoiced).value<QColor>()); ui->playedPushButton->setIcon(QIcon(pixmap)); pixmap.fill(m_lrcSelectedBg = M_SETTING->value(MusicSettingManager::LrcBgColorChoiced).value<QColor>()); ui->noPlayedPushButton->setIcon(QIcon(pixmap)); ui->showLabel->setLinearGradient(m_lrcSelectedFg, m_lrcSelectedBg); ui->showLabel->update(); } ui->transparentSlider->setValue(M_SETTING->value(MusicSettingManager::LrcColorTransChoiced).toInt()); //////////////////////////////////////////////// ui->DfontComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::DLrcFamilyChoiced).toInt()); ui->DfontSizeComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::DLrcSizeChoiced).toInt() - 24); ui->DfontTypeComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::DLrcTypeChoiced).toInt()); if(M_SETTING->value(MusicSettingManager::DLrcColorChoiced).toInt() != -1) { ui->DfontDefaultColorComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::DLrcColorChoiced).toInt()); } else { ui->DfontDefaultColorComboBox->setCurrentIndex(-1); QPixmap pixmap(16, 16); pixmap.fill(m_DlrcSelectedFg = M_SETTING->value(MusicSettingManager::DLrcFgColorChoiced).value<QColor>()); ui->DplayedPushButton->setIcon(QIcon(pixmap)); pixmap.fill(m_DlrcSelectedBg = M_SETTING->value(MusicSettingManager::DLrcBgColorChoiced).value<QColor>()); ui->DnoPlayedPushButton->setIcon(QIcon(pixmap)); ui->DshowLabel->setLinearGradient(m_DlrcSelectedFg, m_DlrcSelectedBg); ui->DshowLabel->update(); } ui->DtransparentSlider->setValue(M_SETTING->value(MusicSettingManager::DLrcColorTransChoiced).toInt()); //////////////////////////////////////////////// ui->downloadDirEdit->setText(M_SETTING->value(MusicSettingManager::DownloadMusicPathDirChoiced).toString()); ui->downloadLrcDirEdit->setText(M_SETTING->value(MusicSettingManager::DownloadLrcPathDirChoiced).toString()); ui->downloadSpinBox->setValue(M_SETTING->value(MusicSettingManager::DownloadCacheSizeChoiced).toInt()); M_SETTING->value(MusicSettingManager::DownloadCacheLimitChoiced).toInt() == 1 ? ui->downloadCacheAutoRadioBox->click() : ui->downloadCacheManRadioBox->click(); #ifdef MUSIC_QT_5 ui->downloadLimitSpeedComboBox->setCurrentText(M_SETTING->value(MusicSettingManager::DownloadDLoadLimitChoiced).toString()); ui->uploadLimitSpeedComboBox->setCurrentText(M_SETTING->value(MusicSettingManager::DownloadULoadLimitChoiced).toString()); #else setComboboxText(ui->downloadLimitSpeedComboBox, M_SETTING->value(MusicSettingManager::DownloadDLoadLimitChoiced).toString()); setComboboxText(ui->uploadLimitSpeedComboBox, M_SETTING->value(MusicSettingManager::DownloadULoadLimitChoiced).toString()); #endif M_SETTING->value(MusicSettingManager::DownloadLimitChoiced).toInt() == 1 ? ui->downloadFullRadioBox->click() : ui->downloadLimitRadioBox->click(); /////////////////////////////////////////////////////////////////////////// ui->downloadServerComboBox->setCurrentIndex(M_SETTING->value(MusicSettingManager::DownloadServerChoiced).toInt()); ui->closeNetWorkCheckBox->setChecked(M_SETTING->value(MusicSettingManager::CloseNetWorkChoiced).toInt()); ui->setDefaultPlayerCheckBox->setChecked(M_SETTING->value(MusicSettingManager::FileAssociationChoiced).toInt()); if(ui->setDefaultPlayerCheckBox->isChecked()) { ui->setDefaultPlayerCheckBox->setEnabled(false); } }
void draw(SkCanvas* canvas) { SkPixmap pixmap(SkImageInfo::MakeA8(16, 32), nullptr, 64); SkDebugf("pixmap height: %d info height: %d\n", pixmap.height(), pixmap.info().height()); }
void TKComboBox::paintEvent(QPaintEvent*) { QRect r; if (editable()){ #ifdef __GNUC__ #warning "Left out for now, lacking a style expert (Werner)" #endif //r = QRect( style().comboButtonRect( 0, 0, width(), height() ) ); r = QRect(4, 2, width()-height()-2, height()-4); } else { r = QRect(4, 2, width()-height()-2, height()-4); } int by = 2; int bx = r.x() + r.width(); int bw = width() - bx - 2; int bh = height()-4; QPainter p( this ); const QColorGroup& g = colorGroup(); QRect fr(2,2,width()-4,height()-4); if ( hasFocus()) { p.fillRect( fr, g.brush( QColorGroup::Highlight ) ); } else { p.fillRect( fr, g.brush( QColorGroup::Base ) ); } QRect r1(1,1,width()-1,height()-1); qDrawShadePanel( &p, r1, g, true, 1 ); static const char* arrow_down[] = { "7 7 2 1", "X c Gray0", " c None", "XXXXXXX", "XXXXXXX", " ", "XXXXXXX", " XXXXX ", " XXX ", " X "}; QPixmap pixmap(arrow_down); style().drawControl( QStyle::CE_PushButton, &p, this, QRect( bx, by, bw, bh ), colorGroup() ); style().drawItem( &p, QRect( bx, by, bw, bh), AlignCenter, colorGroup(), isEnabled(), &pixmap, QString::null ); if ( hasFocus()) { style().drawPrimitive( QStyle::PE_FocusRect, &p, fr, g ); } if (!editable()) { p.setClipRect(r); p.setPen( g.text() ); p.setBackgroundColor( g.background() ); if ( listBox()->item(currentItem()) ) { QListBoxItem * item = listBox()->item(currentItem()); const QPixmap *pix = item->pixmap(); QString text = item->text(); int x = r.x(); if ( pix ) { p.drawPixmap( x, r.y() + ( r.height() - pix->height() ) / 2 +1, *pix ); x += pix->width()+3; } if (!text.isEmpty()) p.drawText( x, r.y(), r.width()-x, r.height(), AlignLeft|AlignVCenter|SingleLine, text ); } } p.end(); }
void MyShip::cllsn_dtctn() { QList<QGraphicsItem *> clldng_items = collidingItems(Qt::ItemSelectionMode::IntersectsItemShape); foreach(QGraphicsItem *i, clldng_items) { if (dynamic_cast<MyLife *>(i) && dynamic_cast<MyLife *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_lf_add)); lf++; dynamic_cast<MyLife *>(i)->hide(); } else if (dynamic_cast<MyMagic *>(i) && dynamic_cast<MyMagic *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_mgc_add)); activate_mgc(); dynamic_cast<MyMagic *>(i)->hide(); } else if (dynamic_cast<MyShield *>(i) && dynamic_cast<MyShield *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_shld_add)); activate_shld(); dynamic_cast<MyShield *>(i)->hide(); } else if (dynamic_cast<MyShip *>(i) && dynamic_cast<MyShip *>(i)->isVisible() && !lf_tmr->isActive()) { ply_sf(const_cast<QString &>(MyRes::sf_shp_shp_add)); lf--; activate_lf(); } else if (dynamic_cast<MyShipShield *>(i) && dynamic_cast<MyShipShield *>(i)->isVisible() && dynamic_cast<MyShipShield *>(i) != shpshld) { ply_sf(const_cast<QString &>(MyRes::sf_expln_shpshld_add)); if (!lf_tmr->isActive()) { lf--; activate_lf(); } dynamic_cast<MyShipShield *>(i)->dstry(); } else if (dynamic_cast<MyStar *>(i) && dynamic_cast<MyStar *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_str_add)); scr++; dynamic_cast<MyStar *>(i)->hide(); } else if (dynamic_cast<MyAlien *>(i) && dynamic_cast<MyAlien *>(i)->isVisible()) { if (dynamic_cast<MyAlien *>(i)->getTyp() == 0) { ply_sf(const_cast<QString &>(MyRes::sf_expln_aln_bg_add)); MyExplosion *expln = new MyExplosion(const_cast<QSize *>(&MyRes::expln_aln_bg_size)); expln->setPos(dynamic_cast<MyAlien *>(i)->x() + (dynamic_cast<MyAlien *>(i)->pixmap().width() / 2) - (MyRes::expln_aln_bg_size.width() / 2), dynamic_cast<MyAlien *>(i)->y() + (dynamic_cast<MyAlien *>(i)->pixmap().height() / 2) - (MyRes::expln_aln_bg_size.height() / 2) + MyRes::expln_aln_bg_crrctn); scene()->addItem(expln); } else { ply_sf(const_cast<QString &>(MyRes::sf_expln_aln_smll_add)); MyExplosion *expln = new MyExplosion(const_cast<QSize *>(&MyRes::expln_aln_smll_size)); expln->setPos(dynamic_cast<MyAlien *>(i)->x() + (dynamic_cast<MyAlien *>(i)->pixmap().width() / 2) - (MyRes::expln_aln_smll_size.width() / 2), dynamic_cast<MyAlien *>(i)->y() + (dynamic_cast<MyAlien *>(i)->pixmap().height() / 2) - (MyRes::expln_aln_smll_size.height() / 2) + MyRes::expln_aln_smll_crrctn); scene()->addItem(expln); } if (!lf_tmr->isActive()) { lf--; activate_lf(); } dynamic_cast<MyAlien *>(i)->killTimer(dynamic_cast<MyAlien *>(i)->getTmr_id()); dynamic_cast<MyAlien *>(i)->hide(); } else if (dynamic_cast<MyAlienBoss *>(i) && dynamic_cast<MyAlienBoss *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_expln_astrd_add)); if (dynamic_cast<MyAlienBoss *>(i)->getStg() == 0) { MyExplosion *expln = new MyExplosion(const_cast<QSize *>(&MyRes::expln_astrd_size)); expln->setPos( dynamic_cast<MyAlienBoss *>(i)->x() + (dynamic_cast<MyAlienBoss *>(i)->pixmap().width() / 2) - (MyRes::expln_astrd_size.width() / 2), dynamic_cast<MyAlienBoss *>(i)->y() + (dynamic_cast<MyAlienBoss *>(i)->pixmap().height() / 2) - (MyRes::expln_astrd_size.height() / 2) + MyRes::expln_astrd_crrctn); expln->updt(); scene()->addItem(expln); } if (!lf_tmr->isActive()) { lf--; activate_lf(); } dynamic_cast<MyAlienBoss *>(i)->hide(); if (dynamic_cast<MyAlienBoss *>(i)->getStg() != 0) { for (int j = -1; j <= 1; j += 2) { MyAlienBoss *bss = new MyAlienBoss(dynamic_cast<MyAlienBoss *>(i)->getStg() - 1, j, j); if (j == -1) { bss->setPos(dynamic_cast<MyAlienBoss *>(i)->pos().x(), sceneBoundingRect().top() - 100); } else { bss->setPos(dynamic_cast<MyAlienBoss *>(i)->pos().x(), sceneBoundingRect().bottom()); } scene()->addItem(bss); } } } else if (dynamic_cast<MyAsteroid *>(i) && dynamic_cast<MyAsteroid *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_expln_astrd_add)); MyExplosion *expln = new MyExplosion(const_cast<QSize *>(&MyRes::expln_astrd_size)); expln->setPos( dynamic_cast<MyAsteroid *>(i)->x() + (dynamic_cast<MyAsteroid *>(i)->pixmap().width() / 2) - (MyRes::expln_astrd_size.width() / 2), dynamic_cast<MyAsteroid *>(i)->y() + (dynamic_cast<MyAsteroid *>(i)->pixmap().height() / 2) - (MyRes::expln_astrd_size.height() / 2) + MyRes::expln_astrd_crrctn); expln->updt(); scene()->addItem(expln); if (!lf_tmr->isActive()) { lf--; activate_lf(); } dynamic_cast<MyAsteroid *>(i)->hide(); } else if (dynamic_cast<MyBullet *>(i) && dynamic_cast<MyBullet *>(i)->getDir() == -1 && dynamic_cast<MyBullet *>(i)->isVisible()) { ply_sf(const_cast<QString &>(MyRes::sf_expln_lsr_add)); MyExplosion *expln = new MyExplosion(const_cast<QSize *>(&MyRes::expln_lsr_size)); expln->setPos(dynamic_cast<MyBullet *>(i)->x() + (dynamic_cast<MyBullet *>(i)->pixmap().width() / 2) - (MyRes::expln_lsr_size.width() / 2), dynamic_cast<MyBullet *>(i)->y() + (dynamic_cast<MyBullet *>(i)->pixmap().height() / 2) - (MyRes::expln_lsr_size.height() / 2) + MyRes::expln_lsr_crrctn); expln->updt(); scene()->addItem(expln); if (!lf_tmr->isActive()) { lf--; activate_lf(); } dynamic_cast<MyBullet *>(i)->hide(); } else if (dynamic_cast<MyGravityField *>(i) && dynamic_cast<MyGravityField *>(i)->isVisible()) { dynamic_cast<MyGravityField *>(i)->getPar()->setPos(pos().x() + pixmap().width() / 2 - dynamic_cast<MyGravityField *>(i)->boundingRect().width() / 2, pos().y() + pixmap().height() / 2 - dynamic_cast<MyGravityField *>(i)->boundingRect().height() / 2); } } }
void QRImageWidget::copyImage() { if(!pixmap()) return; QApplication::clipboard()->setImage(exportImage()); }
void MyShip::updt_vlc(QSet<int> *prsd_kys) { vlc->setY(0); vlc->setX(0); if (prsd_kys->find(Qt::Key_Up) != prsd_kys->end() && name->compare("1") == 0) { vlc->setY(vlc->y() - MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_Down) != prsd_kys->end() && name->compare("1") == 0) { vlc->setY(vlc->y() + MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_Left) != prsd_kys->end() && name->compare("1") == 0) { vlc->setX(vlc->x() - MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_Right) != prsd_kys->end() && name->compare("1") == 0) { vlc->setX(vlc->x() + MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_Space) != prsd_kys->end() && name->compare("1") == 0 && lsr) { ply_sf(const_cast<QString &>(MyRes::sf_shp_lsr_add)); if (!mgc) { MyBullet *lsr = new MyBullet(0); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } else { for (int i = -MyRes::lsr_rtn_max; i <= MyRes::lsr_rtn_max; i += MyRes::lsr_rtn_stp) { MyBullet *lsr = new MyBullet(0, i); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } } deactivate_lsr(); } if (prsd_kys->find(Qt::Key_W) != prsd_kys->end() && name->compare("2") == 0) { vlc->setY(vlc->y() - MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_S) != prsd_kys->end() && name->compare("2") == 0) { vlc->setY(vlc->y() + MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_A) != prsd_kys->end() && name->compare("2") == 0) { vlc->setX(vlc->x() - MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_D) != prsd_kys->end() && name->compare("2") == 0) { vlc->setX(vlc->x() + MyRes::shp_mvmnt); } if (prsd_kys->find(Qt::Key_X) != prsd_kys->end() && name->compare("2") == 0 && lsr) { ply_sf(const_cast<QString &>(MyRes::sf_shp_lsr_add)); if (!mgc) { MyBullet *lsr = new MyBullet(0); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } else { for (int i = -MyRes::lsr_rtn_max; i <= MyRes::lsr_rtn_max; i += MyRes::lsr_rtn_stp) { MyBullet *lsr = new MyBullet(0, i); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } } deactivate_lsr(); } if (prsd_kys->find(-Qt::Key_W) != prsd_kys->end() && name->compare("ai") == 0) { vlc->setY(vlc->y() - MyRes::shp_mvmnt); } if (prsd_kys->find(-Qt::Key_S) != prsd_kys->end() && name->compare("ai") == 0) { vlc->setY(vlc->y() + MyRes::shp_mvmnt); } if (prsd_kys->find(-Qt::Key_A) != prsd_kys->end() && name->compare("ai") == 0) { vlc->setX(vlc->x() - MyRes::shp_mvmnt); } if (prsd_kys->find(-Qt::Key_D) != prsd_kys->end() && name->compare("ai") == 0) { vlc->setX(vlc->x() + MyRes::shp_mvmnt); } if (prsd_kys->find(-Qt::Key_X) != prsd_kys->end() && name->compare("ai") == 0 && lsr) { ply_sf(const_cast<QString &>(MyRes::sf_shp_lsr_add)); if (!mgc) { MyBullet *lsr = new MyBullet(0); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } else { for (int i = -MyRes::lsr_rtn_max; i <= MyRes::lsr_rtn_max; i += MyRes::lsr_rtn_stp) { MyBullet *lsr = new MyBullet(0, i); lsr->setPos(pos().x() + pixmap().width(), pos().y() + (pixmap().height() / 2) - (MyRes::lsr_size.height() / 2)); scene()->addItem(lsr); QObject::connect(lsr, SIGNAL(scrGained()), this, SLOT(scrIncrement())); } } deactivate_lsr(); } }
loginFrame::loginFrame(QTcpSocket *socket,QWidget *parent) : QMainWindow(parent), ui(new Ui::loginFrame) { ui->setupUi(this); aboutDlg = new aboutDialog(); connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(loginSlot())); this->socket = socket; connect(ui->label_4,SIGNAL(linkActivated(QString)),this,SLOT(showRegisterDlg())); connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(error())); errorBox = new QMessageBox(this); connect(ui->comboBox,SIGNAL(activated(int)),this,SLOT(setSelectedText(int))); connect(ui->comboBox,SIGNAL(highlighted(int)),this,SLOT(showSelectedItem(int))); ui->comboBox_2->view()->setFixedWidth(50); connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(showSettingPanel())); //右键菜单 ui->comboBox->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->comboBox,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(showContextMenu(QPoint))); menu = new QMenu(ui->comboBox); deleteAction = menu->addAction(QIcon(":/images/no.jpg") ,QString::fromLocal8Bit("删除账号信息")); selectAction = menu->addAction(QIcon(":/images/yes.jpg") ,QString::fromLocal8Bit("选择账号")); connect(deleteAction,SIGNAL(triggered(bool)),this,SLOT(deleteUserInfo())); connect(selectAction,SIGNAL(triggered(bool)),this,SLOT(selectUserInfo())); //变量初始化 this->isAutoLogin = false; this->isSavePassword = false; connect(ui->checkBox_password,SIGNAL(stateChanged(int)),this,SLOT(setSavePassword(int))); connect(ui->checkBox_autoLogin,SIGNAL(stateChanged(int)),this,SLOT(setAutoLogin(int))); // connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(autoWritePasw(int))); connect(ui->comboBox->lineEdit(),SIGNAL(textChanged(QString)),this,SLOT(setEditState())); this->isauto = false; readRegistryData(); timer = new QTimer(); timer->setInterval(1000); timer->setSingleShot(true); //如果在构造函数未完成就直接登录,会发生异常,所以等构造完一段时间后再自动登录 connect(timer,SIGNAL(timeout()),this,SLOT(autoLogin())); timer->start(); //背景 this->setWindowFlags(Qt::FramelessWindowHint); QPixmap pixmap(":/images/about_Back.png"); QPixmap pixmap2 = pixmap.scaled(this->size()); QPalette palette; palette.setBrush(this->backgroundRole(),QBrush(pixmap2) ); this->setPalette(palette); this->setMask(pixmap2.mask()); this->setAutoFillBackground(true); this->setMouseTracking(true); //最小化和关闭按钮 ui->pushButton_min->setStyleSheet( "QPushButton { background-image: url(:/images/min.bmp); }" "QPushButton:hover { background-image: url(:/images/min_highlight.bmp); }" "QPushButton:pressed { background-image: url(:/images/min_pushed.bmp); }"); ui->pushButton_close->setStyleSheet( "QPushButton { background-image: url(:/images/colse_normal.bmp); }" "QPushButton:hover { background-image: url(:/images/close_highlight.bmp); }" "QPushButton:pressed { background-image: url(:/images/close_pushed.bmp); }"); connect(ui->pushButton_min,SIGNAL(clicked()),this,SLOT(showMinimized())); connect(ui->pushButton_close,SIGNAL(clicked()),this,SLOT(close())); //事件过滤器,点击logo时显示about窗口 ui->label_logo->installEventFilter(this); //系统设置面板 connect(ui->checkBox_password_2,SIGNAL(stateChanged(int)),this,SLOT(setSavePassword(int))); connect(ui->checkBox_autoLogin_2,SIGNAL(stateChanged(int)),this,SLOT(setAutoLogin(int))); this->test_socket = new QTcpSocket(); connect(ui->pushButton_test,SIGNAL(clicked()),this,SLOT(testServerConnection())); connect(this->test_socket,SIGNAL(connected()),this,SLOT(showTestConnected())); connect(this->test_socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(showTestError(QAbstractSocket::SocketError))); connect(ui->pushButton_cancel,SIGNAL(clicked()),this,SLOT(settingCancel())); connect(ui->pushButton_ok,SIGNAL(clicked()),this,SLOT(settingOK())); }
void tst_QPixmapFilter::convolutionDrawSubRect() { QPixmapConvolutionFilter filter; qreal kernel[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1 }; filter.setConvolutionKernel(kernel, 3, 3); QPixmap pixmap("noise.png"); QImage result(pixmap.size(), QImage::Format_ARGB32_Premultiplied); QPainter painter(&result); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect(result.rect(), QColor(128, 0, 0, 255)); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); filter.draw(&painter, QPointF(16, 16), pixmap, QRectF(16, 16, 16, 16)); painter.end(); QImage resultImg = result; QImage sourceImg = pixmap.toImage(); for(int y = 0; y < resultImg.height()-1; y++) { for(int x = 0; x < resultImg.width()-1; x++) { QRgb pixel = resultImg.pixel(x,y); QRgb srcPixel = sourceImg.pixel(x+1,y+1); if(x>=15 && x<33 && y>=15 && y<33) { QCOMPARE(pixel, srcPixel); } else { QCOMPARE(qRed(pixel), 128); QCOMPARE(qGreen(pixel), 0); QCOMPARE(qBlue(pixel), 0); QCOMPARE(qAlpha(pixel), 255); } } } kernel[2] = 1; kernel[8] = 0; filter.setConvolutionKernel(kernel, 3, 3); QPainter painter2(&result); painter2.setCompositionMode(QPainter::CompositionMode_Source); painter2.fillRect(result.rect(), QColor(128, 0, 0, 255)); painter2.setCompositionMode(QPainter::CompositionMode_SourceOver); filter.draw(&painter2, QPointF(16, 16), pixmap, QRectF(16, 16, 16, 16)); painter2.end(); resultImg = result; sourceImg = pixmap.toImage(); for(int y = 1; y < resultImg.height(); y++) { for(int x = 0; x < resultImg.width()-1; x++) { QRgb pixel = resultImg.pixel(x,y); QRgb srcPixel = sourceImg.pixel(x+1,y-1); if(x>=15 && x<33 && y>=15 && y<33) { QCOMPARE(pixel, srcPixel); } else { QCOMPARE(qRed(pixel), 128); QCOMPARE(qGreen(pixel), 0); QCOMPARE(qBlue(pixel), 0); QCOMPARE(qAlpha(pixel), 255); } } } }