Russian Qt Forum
Май 05, 2024, 19:19 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало   Форум  WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  

Страниц: 1 [2]   Вниз
  Печать  
Автор Тема: QComboBox - текст айтемов разными цветами  (Прочитано 6493 раз)
GreatSnake
Джедай : наставник для всех
*******
Offline Offline

Сообщений: 2921



Просмотр профиля
« Ответ #15 : Сентябрь 19, 2011, 13:13 »

Код
C++ (Qt)
#include <QApplication>
#include <QComboBox>
#include <QStandardItemModel>
#include <QStylePainter>
 
class ComboBox : public QComboBox
{
public:
ComboBox( QWidget* p = 0 ) : QComboBox( p ) {}
 
protected:
void paintEvent( QPaintEvent* )
{
QModelIndex mi = model()->index( currentIndex(), 0 );
QPalette pal = palette();
 
QVariant v = mi.data( Qt::BackgroundRole );
if( v.isValid() )
pal.setColor( QPalette::Button, qvariant_cast< QColor >( v ) );
v = mi.data( Qt::ForegroundRole );
if( v.isValid() )
pal.setColor( QPalette::ButtonText, qvariant_cast< QColor >( v ) );
 
QStylePainter painter( this );
 
QStyleOptionComboBox opt;
initStyleOption( &opt );
opt.palette = pal;
 
painter.drawComplexControl( QStyle::CC_ComboBox, opt );
painter.drawControl( QStyle::CE_ComboBoxLabel, opt );
}
};
 
int main( int argc, char** argv )
{
QApplication app( argc, argv );
 
ComboBox cb;
char *colors[] = { "brown", "orange", "yellow", "green", "lightblue", "blue", "purple" };
QStandardItemModel* m = qobject_cast< QStandardItemModel* >( cb.model() );
 
m->setRowCount( 7 );
for( int i = 0; i < 7; i++ )
{
QModelIndex mi = m->index( i, 0 );
m->setData( mi, colors[i], Qt::DisplayRole );
QColor c = QColor( colors[i] );
m->setData( mi, c, Qt::BackgroundRole );
m->setData( mi, QColor( qGray( c.rgb() ) < 128 ? Qt::white : Qt::black ), Qt::ForegroundRole );
m->setData( mi, c, Qt::DecorationRole );
}
 
cb.show();
return app.exec();
}
 
Записан

Qt 5.11/4.8.7 (X11/Win)
Страниц: 1 [2]   Вверх
  Печать  
 
Перейти в:  


Страница сгенерирована за 0.081 секунд. Запросов: 22.