Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > С/С++: Кроссплатформенное программирование, Qt/Gtk+/wxWidgets > [QT3.3]программирование в designer qt-3.3


Автор: rolandast 24.11.2008, 14:22
Недавно начал разбираться с qt designer. Создаю кнопку, хочу чтобы после нажатия на нее вылазило окошко, но ничего не получается. Не подскажите как это сделать? Оч нужно!!! 

Автор: Elfebet 24.11.2008, 15:11
ты хочеш чтобы в qt designer при нажатии на кнопку окошко вылазило?  smile 
наверное ты имел ввиду что код неполучаеться написать для отображения окна?
Код

QDialog *dlg = new QDialog(this);
dlg->exec();

покажи где неполучаеться - поправим
а так посмотри в примерах qt "./examples/"

Автор: rolandast 25.11.2008, 10:12
да. насчет того что код писать надо я понял тока не могу понять где его нужно прописать. решил сделать в качестве примера такое окно: создаю 2 кнопки в designer: pushButton here  и exit. Создал окошко в котором написано Hello. Теперь хочу нажать на  pushButton here и вызвать Hello. Для pushButton here создал в меню Edit/Connections функцию text_call. вот мэновский файл:
Код

#include <qapplication.h>
#include "helloform.h"
#include "textform.h"

int main( int argc, char ** argv )
{
    QApplication app( argc, argv );
    HelloForm w;
    w.show();
    
    app.connect( &app, SIGNAL( lastWindowClosed() ), &app, SLOT( quit() ) );
    return app.exec();
}


а вот код, который появился в в ui.h
Код

void HelloForm::text_call()
{
    
}



вот я и не знаю где в каком файле что прописать. В примерах смотрел но на мой случай ничего не нашел. Да их большинство для qt4.

Автор: Elfebet 25.11.2008, 10:32
если ты все правильно сделал то добавь в функцию text_call
Код

    Textform w;
    w.show();


Автор: rolandast 25.11.2008, 10:51
все так сделал - ничего не выходит. все компилируется работает тока exit

Автор: Elfebet 25.11.2008, 12:05
приведи весь код проекта или выложи здесь его в архиве, неохота гадать где ошибка

p.s. а вообще намного удобней вручную создавать виджеты и выставлять сигналы и слоты - так ты быстрее поймеш что к чему и как это работает

Автор: rolandast 25.11.2008, 12:28
helloform.cpp
Код

/****************************************************************************
** Form implementation generated from reading ui file 'helloform.ui'
**
** Created by: The User Interface Compiler ($Id: qt/main.cpp   3.3.6   edited Aug 31 2005 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/

#include "helloform.h"

#include <qvariant.h>
#include <qpushbutton.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>

#include "helloform.ui.h"
/*
 *  Constructs a HelloForm as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
HelloForm::HelloForm( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
    if ( !name )
    setName( "HelloForm" );
    setAcceptDrops( FALSE );

    QWidget* privateLayoutWidget = new QWidget( this, "layout2" );
    privateLayoutWidget->setGeometry( QRect( 20, 10, 217, 85 ) );
    layout2 = new QGridLayout( privateLayoutWidget, 1, 1, 11, 6, "layout2"); 
    spacer1 = new QSpacerItem( 91, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
    layout2->addMultiCell( spacer1, 0, 1, 1, 2 );

    pushButton = new QPushButton( privateLayoutWidget, "pushButton" );
    pushButton->setAutoRepeat( TRUE );

    layout2->addMultiCellWidget( pushButton, 0, 1, 0, 0 );
    spacer2 = new QSpacerItem( 20, 41, QSizePolicy::Minimum, QSizePolicy::Expanding );
    layout2->addItem( spacer2, 1, 2 );

    ExitButton = new QPushButton( privateLayoutWidget, "ExitButton" );

    layout2->addMultiCellWidget( ExitButton, 2, 2, 1, 2 );
    languageChange();
    resize( QSize(257, 105).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );

    // signals and slots connections
    connect( pushButton, SIGNAL( clicked() ), this, SLOT( text_call() ) );
    connect( ExitButton, SIGNAL( clicked() ), this, SLOT( close() ) );
}

/*
 *  Destroys the object and frees any allocated resources
 */
HelloForm::~HelloForm()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void HelloForm::languageChange()
{
    setCaption( tr( "hello" ) );
    pushButton->setText( tr( "pushButton here" ) );
    ExitButton->setText( tr( "exit" ) );
}



helloform.h
Код

/****************************************************************************
** Form interface generated from reading ui file 'helloform.ui'
**
** Created by: The User Interface Compiler ($Id: qt/main.cpp   3.3.6   edited Aug 31 2005 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/

#ifndef HELLOFORM_H
#define HELLOFORM_H

#include <qvariant.h>
#include <qdialog.h>

class QVBoxLayout;
class QHBoxLayout;
class QGridLayout;
class QSpacerItem;
class QPushButton;

class HelloForm : public QDialog
{
    Q_OBJECT

public:
    HelloForm( QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0 );
    ~HelloForm();

    QPushButton* pushButton;
    QPushButton* ExitButton;

public slots:
    virtual void text_call();

protected:
    QGridLayout* layout2;
    QSpacerItem* spacer1;
    QSpacerItem* spacer2;

protected slots:
    virtual void languageChange();

};

#endif // HELLOFORM_H



textform.cpp
Код

/****************************************************************************
** Form implementation generated from reading ui file 'textform.ui'
**
** Created by: The User Interface Compiler ($Id: qt/main.cpp   3.3.6   edited Aug 31 2005 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/

#include "textform.h"

#include <qvariant.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>

/*
 *  Constructs a textForm as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
textForm::textForm( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
    if ( !name )
    setName( "textForm" );
    textFormLayout = new QHBoxLayout( this, 11, 6, "textFormLayout"); 

    textLabel1 = new QLabel( this, "textLabel1" );
    textFormLayout->addWidget( textLabel1 );
    languageChange();
    resize( QSize(124, 97).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );
}

/*
 *  Destroys the object and frees any allocated resources
 */
textForm::~textForm()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void textForm::languageChange()
{
    setCaption( tr( "text" ) );
    textLabel1->setText( tr( "<h3>\n"
"<i>\n"
"<body>\n"
"<p align=center>\n"
"<font color=red> Hello </font></i> <h1>\n"
"<p align=center>\n"
"<font color=blue>QT</font ></h1></p>\n"
"</body>\n"
"</h3>" ) );
}




textform.h
Код

/****************************************************************************
** Form implementation generated from reading ui file 'textform.ui'
**
** Created by: The User Interface Compiler ($Id: qt/main.cpp   3.3.6   edited Aug 31 2005 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/

#include "textform.h"

#include <qvariant.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>

/*
 *  Constructs a textForm as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 *  The dialog will by default be modeless, unless you set 'modal' to
 *  TRUE to construct a modal dialog.
 */
textForm::textForm( QWidget* parent, const char* name, bool modal, WFlags fl )
    : QDialog( parent, name, modal, fl )
{
    if ( !name )
    setName( "textForm" );
    textFormLayout = new QHBoxLayout( this, 11, 6, "textFormLayout"); 

    textLabel1 = new QLabel( this, "textLabel1" );
    textFormLayout->addWidget( textLabel1 );
    languageChange();
    resize( QSize(124, 97).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );
}

/*
 *  Destroys the object and frees any allocated resources
 */
textForm::~textForm()
{
    // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void textForm::languageChange()
{
    setCaption( tr( "text" ) );
    textLabel1->setText( tr( "<h3>\n"
"<i>\n"
"<body>\n"
"<p align=center>\n"
"<font color=red> Hello </font></i> <h1>\n"
"<p align=center>\n"
"<font color=blue>QT</font ></h1></p>\n"
"</body>\n"
"</h3>" ) );
}



ну все

Автор: Elfebet 25.11.2008, 12:47
1.
Код

public slots:
    virtual void text_call();

зачем virtual? убери это.

2. вот ты обьявил функцию, прицепил сигнал, а где сама функция??
Код

void HelloForm:: text_call()
{
    textForm win(this, "text");
    win.show();
}



Автор: rolandast 25.11.2008, 12:56
не знаю.а где ее надо создать?

Автор: Elfebet 25.11.2008, 13:02
Цитата

не знаю.а где ее надо создать? 

в helloform.cpp


ты в программировании первый раз?
почитай какую нибудь литературу о QT, C++

Автор: rolandast 25.11.2008, 13:28
в таком да. у меня уже куча книг, но там трудновато разобраться так сразу.

Добавлено через 6 минут и 17 секунд
все добавил все сделал вылазит такая ошибка - helloform.cpp:73: error: no 'void HelloForm::text_call()' member function declared in class 'HelloForm'
????

Автор: Elfebet 25.11.2008, 13:46
хм... в твоей ошибке говориться что либо функция не обявлена либо ты эту функцию 2 раза написал
если неможеш привести в рабочее состояние программу, кинь проект в архиве я тебе исправлю и ты увидиш в чем твоя ошибка

Автор: rolandast 25.11.2008, 14:04
а куда можна скинуь?

Автор: Elfebet 25.11.2008, 14:46
Цитата

а куда можна скинуь? 

сюда, чуть ниже где вводим сообщения

Автор: ecspertiza 25.11.2008, 16:44
у него походу ф-ция void HelloForm::text_call() прописана ешо в каком то ui.h, просмотри все файлы с помошью какого нить редактора, и найди где она прописана.

Код

void HelloForm:: text_call()
{
    textForm win(this, "text");
    win.show();
}


должно быть тока в helloform.cpp, и мой тебе совет выкинь designer qt-3.3, слава богу уже QT 4.4.3 на дворе, и скачай IDE под QT типа Eclipce.

Автор: rolandast 26.11.2008, 10:09
к Elfebet ->

Добавлено через 12 минут и 8 секунд
Цитата(ecspertiza @ 25.11.2008,  16:44)
у него походу ф-ция void HelloForm::text_call() прописана ешо в каком то ui.h, просмотри все файлы с помошью какого нить редактора, и найди где она прописана.


я уже прописал этот код и удалил файл ui.h.

Автор: Elfebet 26.11.2008, 10:48
я понял в чем грабли  smile 
в функций text_call
Код

    textForm win(this);
    win.show();

этот код создает окно и показывает а при выходе из функции этот класс убивается, поэтому ты и не видиш это окно
так как textForm - это наследник QDialog, то можно вместо win.show()  написать win.exeс(), окно появиться как модальная и главное окно будет неактивно пока ты это окно не закроеш.

а так, в твоем случае нужно через new создать окно и отобразить
Код

    textForm *win = new textForm(this);
    win->show();



p.s. и действительно, выкинь ты этот qt-3.3, используй qt-4.3 или qt-4.4

Автор: rolandast 26.11.2008, 11:05
спасибо))) smile  smile

Добавлено через 7 минут и 20 секунд
a QT4 поддерживает QT3? могу я все тоже самое сдеалть в QT4?или там есть существенная разница?

Автор: Elfebet 26.11.2008, 11:40
Цитата

a QT4 поддерживает QT3?

да, только нужно скомпилировать с флажком -Qt3Support
Цитата

могу я все тоже самое сдеалть в QT4?

да
Цитата

или там есть существенная разница? 

разница есть, но несущественная


вообщем если решил перейти на QT4 то нужно почитать про отличие от QT3

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)